Arrays.binarySearch(T[] a, int fromIndex, int toIndex, T key, Comparator <? super T> c) has the following syntax.
public static <T> int binarySearch(T[] a, int fromIndex, int toIndex, T key, Comparator <? super T> c)
In the following code shows how to use Arrays.binarySearch(T[] a, int fromIndex, int toIndex, T key, Comparator <? super T> c) method.
Binary search needs sorted arrays.
import java.util.Arrays; import java.util.Comparator; // w ww. j a v a 2 s . c o m public class Main { public static void main(String[] args) { // initializing sorted short array Short shortArr[] = new Short[]{1, 2, 15, 52, 110}; // use comparator as null, sorting as natural ordering Comparator<Short> comp = null; // entering the value to be searched short searchVal = 15; // search between index 1 and 4 int retVal = Arrays.binarySearch(shortArr, 1, 4, searchVal, comp); System.out.println("The index of element 15 is : " + retVal); } }
The code above generates the following result.