List VS Set In Java: In this article, we will discuss the difference between List and Set in detail i.e.; List v/s Set
Both interfaces directly extend Collection interface, but they are a few differences between them Lets us move on and discuss key differences between them
List vs Set In Java
List |
Set |
It stores elements according to insertion order, insertion order is preserved | Set stores elements in random order, as it uses hashing techniqueInsertion 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 |
It allows duplicate elements | Set doesn’t allow duplicate elements i.e.; it stores only unique elementsNote: if the same element is added again, there won’t be any compile-time or runtime error, just that add() method returns false; |
Any number of the 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 the 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 a big factor while iterating items
- then Set is the good choice to store the group of elements
- Example: it could be HashSet, etc
If you like SoftwareTestingo and would like to contribute something to this community, then you can also write an article using our Contact us page or mail your article to admin@softwaretestingo.com. So that we can review your article and that also appears on the SoftwareTestingo.com main page and help other Testers.
Please Improve this article, if you find anything incorrect by commenting on the comment box and we are happy to work on the article to maintain the accuracy and improvement.