Java中的Collection和List有什么区别?

What is the difference between Collection and List in Java?

Java中CollectionList有什么区别? 我什么时候应该使用哪个?


首先,ListCollection。但是,它是专门的Collection

Collection就是:项目的集合。您可以添加内容,删除内容,对内容进行迭代并查询其中有多少内容。

List向其添加有关已定义填充序列的信息:您可以在位置n获得元素,可以在位置n添加元素,可以在位置n移除元素。

Collection中,您无法执行此操作:未定义"此集合中的第5个元素",因为没有定义的顺序。

还有其他专门的Collection,例如Set,它添加了一个功能,即它永远不会包含相同的元素两次。


Collection是Java Collections层次结构的根接口。 List是一个子接口,它定义了有序的Collection,其他子接口是Queue,通常将存储准备好进行处理的元素(例如堆栈)。

下图演示了不同的Java集合类型之间的关系:

java collections


Java API是最好的答案

采集

The root interface in the collection
hierarchy. A collection represents a
group of objects, known as its
elements. Some collections allow
duplicate elements and others do not.
Some are ordered and others unordered.
The JDK does not provide any direct
implementations of this interface: it
provides implementations of more
specific subinterfaces like Set and
List. This interface is typically used
to pass collections around and
manipulate them where maximum
generality is desired.

列表(扩展集合)

An ordered collection (also known as a
sequence). The user of this interface
has precise control over where in the
list each element is inserted. The
user can access elements by their
integer index (position in the list),
and search for elements in the list.

Unlike sets, lists typically allow
duplicate elements. More formally,
lists typically allow pairs of
elements e1 and e2 such that
e1.equals(e2), and they typically
allow multiple null elements if they
allow null elements at all. It is not
inconceivable that someone might wish
to implement a list that prohibits
duplicates, by throwing runtime
exceptions when the user attempts to
insert them, but we expect this usage
to be rare.


List和Set是Collection的两个子类。

在列表中,数据按特定顺序排列。

在Set中,它不能包含两次相同的数据。

在Collection中,它只存储没有特定顺序的数据,并且可以包含重复数据。


集合是Java集合层次结构的主要接口,而List(Sequence)是定义有序集合的子接口之一。


Collection是List的超级接口,因此每个Java列表都是collection的实例。集合只能顺序地(且没有特定的顺序)迭代,而列表允许通过get(int index)方法访问特定位置的元素。


集合是描述Java对象的高级接口,其中可以包含其他对象的集合。关于如何访问它们,同一对象的多个副本是否可以存在于同一集合中,或者顺序是否重要,还不是很明确。列表专门是对象的有序集合。如果按特定顺序将对象放入列表,它们将保持该顺序。

与决定使用哪种具体实现相比,决定在哪里使用这两个接口要重要得多。这将影响程序的时间和空间性能。例如,如果您想要一个列表,则可以使用ArrayList或LinkedList,它们中的每一个都会对应用程序产生影响。对于其他集合类型(例如集合),适用类似的注意事项。