【问题标题】:When does algorithms for manipulating random access lists is applied?何时应用操作随机访问列表的算法?
【发布时间】:2013-02-27 16:32:16
【问题描述】:

在 RandomAccess 标记接口描述中是这样写的:

 * <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.

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

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

这个算法什么时候应用,在哪里应用(它是本地代码)?

【问题讨论】:

  • synchronizedList 创建一个数据结构,它不是真正的算法...
  • @OliCharlesworth 是对的,但请参阅文档评论,谈论算法...我在问何时何地应用该算法
  • 你指的是什么算法?
  • RandomAccess 用于检查Collections framework 的成员是否正在实现它,以便像Collection 这样具有算法的库可以在顺序数据结构中的随机访问期间获得性能优势。

标签: java algorithm collections synchronize


【解决方案1】:

其中一个例子是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中所述:

此方法在 log(n) 时间内运行,用于“随机访问”列表(提供接近恒定时间的位置访问)。如果指定的列表没有实现 RandomAccess 接口并且很大,此方法将执行基于迭代器的二分查找,执行 O(n) 链接遍历和 O(log n) 元素比较。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-21
    • 2011-01-02
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多