How to decide which collection should be used from List Set?
This question already has an answer here:
It all depends upon your current requirements
for example, consider some important points about
If you want to access the elements in the same way you're inserting them, then you should use List
because List
is an ordered collection of elements. You can access them using get(int index)
method, whereas no such method is available for Set
. The order in which they will be stored is not guaranteed.
If your elements contains duplicates, then use List
because Set
doesn't allow duplicates whereas if your elements are unique, then you can use Set
.
As far as LinkedList
and ArrayList
are considered:
LinkedList
are slow because they allow only sequential access. But they're good if your elements size is regularly changing, whereas if the size of your elements is fixed, then you should use ArrayList
because they allow fast random read access, so you can grab any element in constant time. ArrayList
are not good when you require large delete operations because adding or removing from anywhere but the end requires shifting all the latter elements over. ArrayList
are not considered good when you have to insert anything in middle because if you want to insert a new element in the middle (and keep all the elements in the same order) then you're going to have to shift everything after that spot where element was inserted, whereas such operation in LinkedList
requires only change of some references. Take a look at the features of several data structures and according to your requirements, you can decide where you should use which data structure.
also see:
- When to use LinkedList over ArrayList?
- What is the difference between Set and List?
- What Java Collection should I use?
- Insertion in the middle of ArrayList vs LinkedList