答案:Collections.binarySearch用于在已排序List中高效查找元素,使用二分查找算法,时间复杂度O(log n),但要求列表必须已按升序排列,否则结果不可预测;方法有两种重载形式,一种适用于元素实现Comparable接口的场景,另一种支持自定义Comparator排序规则;使用前必须确保列表有序,可通过Collections.sort()排序;若找到元素返回其索引(从0开始),未找到则返回-(插入点)-1的负值,表示应插入的位置;对于自定义对象需配合Comparator并按相同规则排序;例如查找年龄为30的Person对象时,需先按age字段排序并提供相应Comparator。

在Java中,Collections.binarySearch 方法用于在已排序的List集合中查找指定元素。它使用二分查找算法,效率高于线性查找,时间复杂度为 O(log n)。但前提是集合必须已经按升序排序,否则结果不可预测。
方法基本语法
该方法属于 java.util.Collections 工具类,常用重载形式如下:
-
public static
int binarySearch(List extends Comparable super T>> list, T key)
适用于列表中的元素实现了 Comparable 接口(如 String、Integer 等)。 -
public static
int binarySearch(List extends T> list, T key, Comparator super T> c)
适用于自定义排序规则,需要提供 Comparator。
使用前提:集合必须有序
binarySearch 要求列表必须是升序排列。如果顺序不对,查找结果可能错误。可使用 Collections.sort() 先排序:
ListCollections.sort(numbers); // 排序:[1, 2, 5, 8]
立即学习“Java免费学习笔记(深入)”;
int index = Collections.binarySearch(numbers, 5); System.out.println("元素5的位置:" + index); // 输出:2
返回值说明
方法返回值有以下几种情况:
- 若找到元素,返回其索引位置(从0开始)。
- 若未找到,返回一个负值,表示“插入点”:-(插入位置) - 1。
例如返回 -3,表示该元素应插入到索引2的位置。
int notFound = Collections.binarySearch(numbers, 7); System.out.println(notFound); // 可能输出 -4,表示7应插入到索引3
自定义对象查找需配合 Comparator
对于自定义类(如 Person),如果想根据某个字段(如年龄)查找,必须提供 Comparator,并确保列表已按该规则排序。
class Person { String name; int age; Person(String name, int age) { this.name = name; this.age = age; } }List
// 按年龄排序 people.sort((a, b) -> Integer.compare(a.age, b.age));
// 使用 Comparator 查找年龄为30的人 int idx = Collections.binarySearch(people, new Person("", 30), (a, b) -> Integer.compare(a.age, b.age)); System.out.println("查找到的位置:" + idx); // 输出 1
基本上就这些。只要记住:排序是前提,返回负数不代表不存在,而是插入位置的提示。用好 binarySearch 能显著提升查找性能。不复杂但容易忽略排序步骤。










