What is the difference between Collection and List in Java?
What is the difference between Collection
and List
in Java? When should I use which?
Solution 1:
First off: a List
is a Collection
. It is a specialized Collection
, however.
A Collection
is just that: a collection of items. You can add stuff, remove stuff, iterate over stuff and query how much stuff is in there.
A List
adds the information about a defined sequence of stuff to it: You can get the element at position n, you can add an element at position n, you can remove the element at position n.
In a Collection
you can't do that: "the 5th element in this collection" isn't defined, because there is no defined order.
There are other specialized Collections as well, for example a Set
which adds the feature that it will never contain the same element twice.
Solution 2:
Collection
is the root interface to the java Collections hierarchy. List
is one sub interface which defines an ordered Collection, other sub interfaces are Queue
which typically will store elements ready for processing (e.g. stack).
The following diagram demonstrates the relationship between the different java collection types:
Solution 3:
Java API is the best to answer this
Collection
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.
List (extends Collection)
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.
Solution 4:
Collection is the Super interface of List so every Java list is as well an instance of collection. Collections are only iterable sequentially (and in no particular order) whereas a List allows access to an element at a certain position via the get(int index)
method.