Using binarySearch with Custom Comparators
What you'll learn: How to ensure binarySearch works correctly when your list was sorted using a custom Comparator.
When you sort a list using a custom Comparator, Java doesn't magically remember how you sorted it. If you later call Collections.binarySearch() using natural ordering (or a different comparator), the search will fail because it's looking for elements based on a different ordering than how they're actually arranged.
The Core Rule: Match Your Comparator
Binary search works by dividing the list in half repeatedly, making decisions based on comparisons. If the search uses different comparison logic than the sort, those decisions will be wrong—like trying to find a book in a library where someone reorganized the shelves using a different system than you're following.
The solution is simple: Pass the exact same Comparator to binarySearch that you used for sorting.
import java.util.*;
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
people.add(new Person("Charlie", 35));
// Sort by age using a custom comparator
Comparator<Person> ageComparator = (p1, p2) -> Integer.compare(p1.age, p2.age);
Collections.sort(people, ageComparator);
// Search using THE SAME comparator
Person target = new Person("", 30);
int index = Collections.binarySearch(people, target, ageComparator);
// Returns the index where age equals 30
Without passing ageComparator to binarySearch, Java would try to use natural ordering (which Person doesn't even have), causing a ClassCastException or incorrect results.
Key Takeaway: Always pass the same Comparator to Collections.binarySearch() that you used in Collections.sort()—mismatched comparators break the binary search algorithm's assumptions.