What is the difference between Collection and List in Java?
Java中
首先,
在
还有其他专门的Collection,例如
下图演示了不同的Java集合类型之间的关系:
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的实例。集合只能顺序地(且没有特定的顺序)迭代,而列表允许通过
集合是描述Java对象的高级接口,其中可以包含其他对象的集合。关于如何访问它们,同一对象的多个副本是否可以存在于同一集合中,或者顺序是否重要,还不是很明确。列表专门是对象的有序集合。如果按特定顺序将对象放入列表,它们将保持该顺序。
与决定使用哪种具体实现相比,决定在哪里使用这两个接口要重要得多。这将影响程序的时间和空间性能。例如,如果您想要一个列表,则可以使用ArrayList或LinkedList,它们中的每一个都会对应用程序产生影响。对于其他集合类型(例如集合),适用类似的注意事项。