Java Collections binarySearch() Method21 Mar 2025 | 4 min read 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)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. SyntaxFollowing is the declaration of binarySearch() method: Parameter
Returns
ExceptionsClassCastException- 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 VersionJava 1.5 and above Example 1Output: index 'D' is available at position: 3 Example 2Output: Provided List are: [10, -20, 30, -40, 50] Index '-20' is available at position: -4 Example 3Output: 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 4Output: 4 is available at index: 3 Example 5Output: Available at index: 0 Found at index: -1 Next TopicJava Collections Class |
We request you to subscribe our newsletter for upcoming updates.