Collections.binarySearch()用于在排序列表中高效查找目标值,时间复杂度为O(log n),使用前必须确保列表已排序,否则结果不可预测;该方法有两个重载版本,分别适用于实现Comparable接口的元素和自定义Comparator比较规则的情况,查找成功返回索引,失败返回-(插入点)-1,可用于优化大型有序数据的搜索性能。

二分查找,简单来说,就是在排序好的列表中快速找到目标值的位置。Java 的
Collections.binarySearch()
Collections.binarySearch() 方法的使用其实挺直接的,但有些细节要注意,不然可能会踩坑。
Collections.binarySearch()
binarySearch(List<? extends Comparable<? super T>> list, T key)
Comparable
立即学习“Java免费学习笔记(深入)”;
binarySearch(List<? extends T> list, T key, Comparator<? super T> c)
Comparator
使用示例(Comparable 接口):
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class BinarySearchExample {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(2);
numbers.add(5);
numbers.add(8);
numbers.add(11);
numbers.add(12);
int index = Collections.binarySearch(numbers, 11);
System.out.println("Index of 11: " + index); // Output: Index of 11: 3
int notFoundIndex = Collections.binarySearch(numbers, 7);
System.out.println("Index of 7: " + notFoundIndex); // Output: Index of 7: -3
}
}使用示例(Comparator 接口):
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class BinarySearchExample {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
names.add("David");
// 按照字符串长度排序
Comparator<String> lengthComparator = Comparator.comparingInt(String::length);
Collections.sort(names, lengthComparator); // 先排序
int index = Collections.binarySearch(names, "Bob", lengthComparator);
System.out.println("Index of Bob: " + index);
}
}返回值:
-(insertion point) - 1
二分查找的核心前提是列表必须是排序好的。如果列表没有排序,
binarySearch()
Collections.binarySearch()
如果列表中有重复的元素,
binarySearch()
Collections.binarySearch()
List
ArrayList
LinkedList
Arrays.binarySearch()
binarySearch()
Collections.binarySearch()
Comparator
Comparator
当然,你可以自己实现二分查找算法。但
Collections.binarySearch()
总的来说,
Collections.binarySearch()
以上就是Java中Collections.binarySearch使用方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号