Difference Between List VS Set In Java

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

It stores elements according to insertion order, insertion order is preservedSet 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 orderWhile iterating Set items, elements will be retrieved in random order
It allows duplicate elementsSet 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 ListMaximum 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.

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment