Arrays.binarySearch(T[] a, T key, Comparator <? super T> c) has the following syntax.
public static <T> int binarySearch(T[] a, T key, Comparator <? super T> c)
In the following code shows how to use Arrays.binarySearch(T[] a, T key, Comparator <? super T> c) method.
Binary search needs sorted arrays.
//from w w w . ja va2s . c om import java.util.Arrays; import java.util.Comparator; 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; int retVal = Arrays.binarySearch(shortArr, searchVal, comp); System.out.println("The index of element 15 is : " + retVal); } }
The code above generates the following result.