Perform Binary Search on ArrayList - Java Collection Framework

Java examples for Collection Framework:ArrayList

Description

Perform Binary Search on ArrayList

Demo Code


import java.util.ArrayList;
import java.util.Collections;
 
public class Main {
 
  public static void main(String[] args) {
    ArrayList arrayList = new ArrayList();
 
    arrayList.add("1");
    arrayList.add("4");
    arrayList.add("2");
    arrayList.add("5");
    arrayList.add("3");
   /* ww  w  .ja v  a2s  .c  o m*/
    Collections.sort(arrayList);
    System.out.println("Sorted ArrayList contains : " + arrayList);
   
    //search an element using binarySearch method of Collections class
    int index = Collections.binarySearch(arrayList,"4");
   
    System.out.println("Element found at : " + index);
  }
}

Result


Related Tutorials