List接口和Collection接口之间的主要区别是什么?

时间:2011-10-14 03:32:18

标签: java list collections

  

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

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

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

看看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)

其中EType中指定的List<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)在所有Collection中都可用。

答案 2 :(得分:0)

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)
  • public ListIterator listIterator()
  • public ListIterator listIterator(int index)
  • public List subList(int fromIndex,int toIndex)

一般来说,

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