简体   繁体   English

为什么 LinkedList 不实现 RandomAccess 接口来使元素的检索更快?

[英]why LinkedList does not implements RandomAccess Interface to make the retrieval of elements faster?

Why only ArrayList and Vector implements RandomAccess interface and LinkedList doesn't?为什么只有 ArrayList 和 Vector 实现了 RandomAccess 接口而 LinkedList 没有? As I understand it, the RandomAccess implemented class can make the retrieval of elements faster in collection.据我了解,RandomAccess 实现的 class 可以使集合中元素的检索速度更快。

Also, if I try to make a custom class which extends java.util.LinkedList and also implements RandomAccess interface, does that make the custom class just like LinkedList but with RandomAccess?另外,如果我尝试制作一个自定义 class 扩展 java.util.LinkedList 并实现 RandomAccess 接口,这是否会使自定义 class 像 LinkedList 一样?

Here is code which is implementing what I stated in the second point:这是实现我在第二点中所述的代码:

public class ExtendedLinkedList extends java.util.LinkedList implements java.util.RandomAccess {
    
    public static void main(String[] args){
        
        ExtendedLinkedList ell = new ExtendedLinkedList();
        
        System.out.println(ell instanceof java.util.RandomAccess); // True
        System.out.println(ell instanceof java.util.LinkedList); // True
    }
    
}

Implementing the RandomAccess interface does not make random access faster.实现RandomAccess接口不会使随机访问更快。

Indeed, it doesn't do anything at all , really.确实,它根本没有做任何事情,真的。

It only exists as a marker interface: it's used to mark list implementations that already provide efficient random indexed access .它仅作为标记接口存在:它用于标记已经提供有效随机索引访问的列表实现。

In other words: ArrayList and Vector implement RandomAccess because they provide efficient random access.换句话说: ArrayListVector实现了RandomAccess ,因为它们提供了有效的随机访问。 LinkedList does not implement it, because it does not provide efficient random access (accessing a specific index from the List interface requires potentially iterating up to half of the list). LinkedList没有实现它,因为它提供有效的随机访问(从List接口访问特定索引可能需要迭代列表的一半)。

If you extend LinkedList then you should not implement RandomAccess unless you also change the implementation of get(int) to be efficient (at which point I'd say you probably shouldn't be extending LinkedList at all).如果您扩展LinkedList ,那么您不应该实现RandomAccess ,除非您还更改了get(int)的实现以提高效率(此时我会说您可能根本不应该扩展LinkedList )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM