Difference between List and Set interface in Java

In this post, we will discuss the difference between List and Set interface in Java.


 

Both List and Set interface are members of the Java Collections Framework. In this post, we will provide an overview of some of the major differences between these two interfaces –

  1. List in Java represents an ordered sequence of elements and its elements can accessible by index. Set in Java represents a distinct collection of elements which can be either ordered or unordered, depending on the implementation. For example, HashSet implementation is unordered, LinkedHashSet implementation is ordered, and TreeSet implementation is ordered by natural order or by provided comparator.
     
  2. Another notable difference between List and Set interface is that the Set contains only distinct elements whereas List allows duplicate elements.
     
  3. List allows any number of null values while a Set can contain at most one null element.
     
  4. Several List implementations implement RandomAccess interface which is a marker interface to support constant time random access. On the other hand, none of the Set implementations can implement the RandomAccess interface.
     
  5. The List interface provides a special iterator ListIterator to facilitate bidirectional access which is not available for Set interface.
     
  6. A List should be used when insertion order of elements needs to maintained. Use a Set if we need to maintain a collection that contains no duplicate element.
     
  7. Popular implementation of List interface includes ArrayList and LinkedList while that of Set interface includes HashSet, TreeSet and LinkedHashSet.

 
References:

1. List Javadoc SE 9
2. Set Javadoc SE 9

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of