This example shows how an element of a java.util.ArrayList can be searched using 'binarySearch' method of java.util.Collections class. This method internally applies binary search algorithm to search a particular element.

Technologies used in this article

  1. JDK 1.6
  2. Eclipse 3.7

1. Create a Java Project and a Class with 'main' method

Create a java project ('BinarySearchDemo') and a class ('BinarySearchExample') in eclipse to run the sample code of binary search on a java.util.ArrayList.

Note: To know how to create a java project in Eclipse IDE, go through the following tutorial "Java Hello World Example using Eclipse IDE".

Sample project structure is shown below
Sample project structure

2. Write Code

Modify your code in the 'main' method as per the following code.

File: BinarySearchExample.java

package com.srccodes.examples.howto;
 
import java.util.ArrayList;
import java.util.Collections;
 
/**
 * @author srccodes.com
 * 
 */
public class BinarySearchExample {
 
    /**
     * @param args
     */
    public static void main(String[] args) {
        // an ArrayList of elements
        ArrayList listToBeSearched = new ArrayList();
 
        // Add elements to the Arraylist
        listToBeSearched.add("4");
        listToBeSearched.add("1");
        listToBeSearched.add("3");
        listToBeSearched.add("7");
        listToBeSearched.add("6");
        listToBeSearched.add("2");
        listToBeSearched.add("5");
 
        // As binary search is performed on a sorted list, listToBeSearched is
        // required to be sorted first before start searching.
        Collections.sort(listToBeSearched);
 
        // See the sorted list in the console
        System.out.println("Sorted List : " + listToBeSearched);
         
        // Search an element from the list using binarySearch method of java.util.Collections class
        int index = Collections.binarySearch(listToBeSearched,"6");
        
        System.out.println("Element position found in the list is " + index);
 
    }
}

3. Run Your Code

Right click on 'BinarySearchExample.java' and select from context menu 'Run As' --> 'Java Application'.

4. Console Output

Your code will print sorted list first then the position of the element found in the list.
Console Output

Download SrcCode

All code samples shown in this post are available in the following link BinarySearchDemo.zip

References