List v/s Set

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 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

 

References:

https://docs.oracle.com/javase/tutorial/collections/intro/
https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
https://docs.oracle.com/javase/tutorial/collections/interfaces/list.html
https://docs.oracle.com/javase/7/docs/api/java/util/List.html
https://docs.oracle.com/javase/tutorial/collections/interfaces/set.html
https://docs.oracle.com/javase/7/docs/api/java/util/Set.html

 

Happy Coding !!
Happy Learning !!

HashSet v/s LinkedHashSet v/s TreeSet
TreeSet class