What is the difference between Collection
and List
in Java? When should I use which?
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.