【问题标题】:what's the main difference between List interface and Collection Interface? [duplicate]List接口和Collection接口的主要区别是什么? [复制]
【发布时间】:2011-10-14 03:32:17
【问题描述】:

可能重复:
What is the difference between List (of T) and Collection(of T)?
What is the difference between Collection and List in Java?

再次使用另一个有什么优点/缺点?使用 Collection 而不是 List 的主要优势是什么?

【问题讨论】:

  • 文档会相当有效地回答这个问题:download.oracle.com/javase/6/docs/api/java/util/List.html。我引用:[a List is] 一个有序集合(也称为序列)。此界面的用户可以精确地控制每个元素在列表中的插入位置。 用户可以通过整数索引访问元素(在列表中的位置),并且在列表中搜索元素..
  • 另外,“使用集合而不是列表”是什么意思?你打算如何实例化集合?你会评估什么具体的实现?
  • 抱歉,我不小心对 .NET 问题投了赞成票。应该是:stackoverflow.com/questions/3317381/…

标签: java list collections


【解决方案1】:

基本上,List 接口允许您执行涉及索引(位置)的操作:检索给定索引中的元素、删除索引中的元素、插入元素等。

集合是一个更通用的接口,有更多的类实现它。

【讨论】:

    【解决方案2】:

    看看the JavaDocs for List

    很多都是这样的,说明他们来自Collection接口:

    指定者:

    size in interface Collection<E>
    

    没有“指定者”部分的有:

    E get(int index)
    
    E set(int index,
          E element)
    
    void add(int index,
             E element)
    
    E remove(int index)
    
    int indexOf(Object o)
    
    int lastIndexOf(Object o)
    
    ListIterator<E> listIterator()
    
    ListIterator<E> listIterator(int index)
    
    List<E> subList(int fromIndex,
                    int toIndex)
    

    其中EList&lt;Type&gt; 中指定的Type

    基本上,它是与索引相关的一堆东西——因为并非所有Collections 都有索引,或者根本就没有顺序,还有一些与特殊迭代器和subList 相关。

    在方法签名中使用Collection 的优点是您不会强制用户使用一种集合(有些用户可以使用Set,有些用户可以使用List,等等)。仅当您不需要 `List 提供的方法时,这才有意义。

    在这个例子中,我没有使用任何List 特定的方法:

    /**
     * Simple example, adds "1" to the Collection
     */
    public static void addOne(Collection in) {
        in.add(1);
    }
    

    没有理由强制此方法的用户只传递一个列表,因为我们调用它的唯一方法 (add) 在所有 Collections 中都可用。

    【讨论】:

      【解决方案3】:

      List 是一个 Collection,但它增加了具有元素order的概念。
      除了Collection的方法,List的还有这些方法:

      • public boolean addAll(int index, Collection c)
      • public E get(int index)
      • public E set(int index, E element)
      • public void add(int index, E element)
      • public E remove(int index)
      • public int indexOf(Object o)
      • public int lastIndexOf(Object o)
      • 公共 ListIterator listIterator()
      • public ListIterator listIterator(int index)
      • 公共列表子列表(int fromIndex,int toIndex)

      一般来说,

      • 当订单很重要和/或可以重复时使用列表。 ArrayList 是一个不错的选择。
      • 当顺序无关紧要和重复不正确时使用 Set。 HashSet 是一个不错的选择。
      • 当订单确实重要且重复不正常时使用 LinkedHashSet

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-28
        • 2014-03-17
        • 2011-04-04
        • 2018-10-19
        • 2015-07-24
        • 2019-10-16
        • 2010-11-13
        • 2013-02-17
        相关资源
        最近更新 更多