java - 何时应用操纵随机访问列表的算法?

标签 java algorithm collections synchronize

在 RandomAccess 标记接口(interface)描述中写道:

 * <p>The best algorithms for manipulating random access lists (such as
 * <tt>ArrayList</tt>) can produce quadratic behavior when applied to
 * sequential access lists (such as <tt>LinkedList</tt>).  Generic list
 * algorithms are encouraged to check whether the given list is an
 * <tt>instanceof</tt> this interface before applying an algorithm that would
 * provide poor performance if it were applied to a sequential access list,
 * and to alter their behavior if necessary to guarantee acceptable
 * performance.

在集合类 synchronizedList 方法中,检查 RandomAccess,如果成功则创建 SynchronizedRandomAccessList 对象,但它们也没有关于算法的详细信息。

public static <T> List<T> synchronizedList(List<T> list) {
    return (list instanceof RandomAccess ?
                new SynchronizedRandomAccessList<T>(list) :
                new SynchronizedList<T>(list));
    }

这个算法什么时候适用以及在哪里(它是 native 代码)?

最佳答案

其中一个示例是 Collections.binarySearch:

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);
}

此处不同的二进制搜索算法实现用于随机访问和顺序访问列表。代码是一个实现细节,但在这里区分列表是合理的。

documenation for Collections.binarySearch 中所述:

This method runs in log(n) time for a "random access" list (which provides near-constant-time positional access). If the specified list does not implement the RandomAccess interface and is large, this method will do an iterator-based binary search that performs O(n) link traversals and O(log n) element comparisons.

关于java - 何时应用操纵随机访问列表的算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15356535/

相关文章:

algorithm - 为什么Graph adjacency不定义为邻接集,而是邻接表?

.net - .NET 中队列 <T> 的大小限制?

data-binding - Asp.net 核心 Razor 页面 [BindProperty] 不适用于集合

java - 在调整大小时缩放地址表单

Java开源类(class)管理系统

algorithm - 在置换方程中查找变量的值

c++ - 倒水 : Graph Implementation Problem - Shortest Path/Dijkstra's (? )

excel - 从项目集合中调用项目

java - java中有更复杂版本的冒泡排序算法吗?

java - Android boolean 偏好问题