为什么Javas Collections框架二进制搜索使用迭代器搜索大列表中的元素
在java文档中: 使用二进制搜索算法在指定列表中搜索指定对象。在进行此调用之前,必须根据其元素的{@linkplain Comparable natural ordering}将列表按升序排序(如通过{@link#sort(list)}方法)。如果未排序,则结果未定义。如果列表包含多个等于指定对象的元素,则无法保证会找到哪个元素 对于“随机访问”列表(提供接近恒定时间的位置访问),此方法以日志(n)时间运行。如果指定的列表未实现{@link RandomAccess}接口且较大,则此方法将执行基于迭代器的二进制搜索,执行O(n)个链接遍历和O(log n)个元素比较 为什么实现使用迭代器来实现大型链表,而链表不实现随机访问为什么Javas Collections框架二进制搜索使用迭代器搜索大列表中的元素,java,algorithm,collections,Java,Algorithm,Collections,在java文档中: 使用二进制搜索算法在指定列表中搜索指定对象。在进行此调用之前,必须根据其元素的{@linkplain Comparable natural ordering}将列表按升序排序(如通过{@link#sort(list)}方法)。如果未排序,则结果未定义。如果列表包含多个等于指定对象的元素,则无法保证会找到哪个元素 对于“随机访问”列表(提供接近恒定时间的位置访问),此方法以日志(n)时间运行。如果指定的列表未实现{@link RandomAccess}接口且较大,则此方法将执行
public static <T>
int binarySearch(List<? extends Comparable<? super T>> list, T key) {
if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)
return Collections.indexedBinarySearch(list, key);
else
return Collections.iteratorBinarySearch(list, key);
}
公共静态
int binarySearch(List好吧,只要继续看源代码,它的解释都很好。
查找BINARYSEARCH\u阈值
静态
字段
/*
* Tuning parameters for algorithms - Many of the List algorithms have
* two implementations, one of which is appropriate for RandomAccess
* lists, the other for "sequential." Often, the random access variant
* yields better performance on small sequential access lists. The
* tuning parameters below determine the cutoff point for what constitutes
* a "small" sequential access list for each algorithm. The values below
* were empirically determined to work well for LinkedList. Hopefully
* they should be reasonable for other sequential access List
* implementations. Those doing performance work on this code would
* do well to validate the values of these parameters from time to time.
* (The first word of each tuning parameter name is the algorithm to which
* it applies.)
*/
private static final int BINARYSEARCH_THRESHOLD = 5000;
实现您正在使用的代码的工程师确定这是最佳的权衡。它不是一成不变的,所以您可以提取
iteratorBinarySearch // or
indexedBinarySearch
如果您认为在您的特定用例中使用迭代器性能更好,请随意使用它们。您的困惑是什么?您认为它还应该做什么?我不明白迭代器如何在搜索实现中为大型数据结构提供更好的性能。在大型列表中使用迭代器的原因是什么,而这些列表不适用于Ment RandomAccess.@dakspratapsingh原因是benchmarks.Oracle工程师(因为该版本来自Oracle JDK)对两个解决方案的性能进行了基准测试,并观察到迭代器解决方案在更大的数据集上表现更好。谢谢,这消除了我的疑问。我认为他们的问题是其背后的一个理论原因。请不要在获得10万分后停止贡献:p。