My question is pretty much the oneliner that makes up the title. When is it appropriate to use the List interface
instead of the Collection interface
?
Is it just a question about clarity and readability, i.e. the intention of the code is clearer if I use either List
or Collection
depending on my code, or are there some other advantages that I'm unaware of?
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 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).
In List, data is in particular order. In Set, it can not contain the same data twice. In Collection, it just stores data with no particular order and can contain duplicate data.
The List interface in Java provides a way to store the ordered collection. It is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements.
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.
One can argue either way, assuming, of course, that you're not dependent on the methods/features of List, and none of the other methods you'll be calling expect List.
There's the argument that it's best to use the most general type that suits the job, to allow code modification/reuse that might lead to switching to a non-List class.
There's also the argument that it's best to use the most specific type that encompasses all planned uses, to have the most power and flexibility within the domain of the planned uses. Using a more specific type also is a sort of self-documentation in that it indicates the narrowness of the code functionality.
In my experience the benefits of code reuse tend to be overstated, and rarely bear fruit outside of code bases that are developed for multiple use. So I'd tend to favor using the more specific type.
When you need the below benefits:
In addition to the operations inherited from Collection, the List interface includes operations for the following:
Listed as
Positional access — manipulates elements based on their numerical position in the list
Search — searches for a specified object in the list and returns its numerical position
Iteration — extends Iterator semantics to take advantage of the list's sequential nature
Range-view — performs arbitrary range operations on the list.
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