可能重复:
What is the difference between List (of T) and Collection(of T)?
What is the difference between Collection and List in Java?
是否有使用另一个的优点/缺点?使用Collection而不是List有什么主要优势?
答案 0 :(得分:1)
基本上,List接口允许您执行涉及索引(位置)的操作:检索给定索引中的元素,删除索引中的元素,插入元素等。
Collection是一个更通用的接口,有更多的类实现它。
答案 1 :(得分:1)
很多人都有这样的行,表明他们来自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)
其中E
是Type
中指定的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还有这些方法:
一般来说,