Java Collections binarySearch() Method
The binarySearch() is an inbuilt method of Java Collections class which returns the position of the object in a sorted list. There are two different types of Java collections binarySearch() method which can be differentiated depending on its parameter.
These are:
- Java Collections binarySearch(List<? extends Comparable<? super T>> list, T key)
- Java Collections binarySearch(List<? extends T> list, T key, Comparator<? super T> c)
Java Collections binarySearch(List<? extends Comparable<? super T>> list, T key)
This method is used to search the provided list for the specified object using the binary search algorithm. The list must be sorted into ascending order according to the specified natural number, prior to making the method call. If the list is not sorted, the results are undefined.
Java Collections binarySearch(List<? extends T> list, T key, Comparator<? super T> c)
This method is used to search the provided list for the specified object using the binary search algorithm. The list must be sorted into ascending order according to the specified comparator prior to making the method call.
Syntax
Following is the declaration of binarySearch() method:
Parameter
Parameter | Description | Required/Optional |
---|---|---|
list | It is specified by user to be searched. | Required |
key | It is the key to be searched for in the provided list. | Required |
c | It is a comparator used for sorting the list. | Required |
Returns
Method | Returns |
---|---|
binarySearch(List<? extends Comparable<? super T>> list, T key) | It returns the index of the key in a sorted list of an ascending order. |
binarySearch(List<? extends T> list, T key, Comparator<? super T> c) | It returns the index of the key in a sorted list of an order defined by comparator c. |
Exceptions
ClassCastException– It throws exception if the elements of the list are not mutually comparable or the search key is not mutually comparable with the elements of the list.
Compatibility Version
Java 1.5 and above
Example 1
Output:
index 'D' is available at position: 3
Example 2
Output:
Provided List are: [10, -20, 30, -40, 50] Index '-20' is available at position: -4
Example 3
Output:
Provided List are: [10, -20, 30] Enter the search key: D Exception in thread "main" java.lang.ClassCastException: java.base/java.lang.Integer cannot be cast to java.base/java.lang.String at java.base/java.lang.String.compareTo(String.java:124) at java.base/java.util.Collections$ReverseComparator.compare(Collections.java:5140) at java.base/java.util.Collections$ReverseComparator.compare(Collections.java:5131) at java.base/java.util.Collections.indexedBinarySearch(Collections.java:333) at java.base/java.util.Collections.binarySearch(Collections.java:321) at myPackage.CollectionBinarySearchExample3.main(CollectionBinarySearchExample3.java:16)
Example 4
Output:
4 is available at index: 3
Example 5
Output:
Available at index: 0 Found at index: -1