What is the difference between Collection
and List
in Java? When should I use which?
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.
The Collections API is a set of classes and interfaces that support operations on collections of objects. Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap. Example of interfaces: Collection, Set, List and Map. Whereas, ArrayList: It is re-sizable array implementation.
It depends on what guarantees you want to provide the user. If the data is sequential such that the order of the elements matter and you are allowing duplicates, then use a list. If order of elements does not matter and duplicates may or may not be allowed, then use a collection.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With