In this article, we will discuss difference between List and Set in detail i.e.; List v/s Set
Both interfaces directly extends Collection interface; but they are few differences between them
Lets us move on and discuss key differences between List and Set
List v/s Set:
|List stores elements according to insertion order
So, insertion order is preserved
|Set stores elements in random order, as it uses hashing technique
Insertion order isn’t preserved
|While iterating List items, elements will be retrieved as per insertion order||While iterating Set items, elements will be retrieved in random order|
|List allows duplicate elements||Set doesn’t allow duplicate elements i.e.; it stores only unique elements
Note: if same element is added again, there won’t be any compile-time or runtime error, just that add() method returns false;
|Any number of NULL object is allowed to add to the List||Maximum of one NULL is allowed|
When to use List?
- If the business requirement is to preserve insertion order and
- adding duplicate elements is not a big concern
- then List is the good choice to store group of elements
- Example: it could be ArrayList or LinkedList or Vector, etc
When to use Set?
- If the business requirement is to avoid storing duplicate elements
- And storing only unique elements
- Where insertion order isn’t big factor while iterating items
- then Set is the good choice to store group of elements
- Example: it could be HashSet, etc
Happy Coding !!
Happy Learning !!