Difference between Set and List in Java

List and Set are two important Java Collection classes. The most important differerences between them are:

  1. Fundamental difference between List and Set in Java is allowing duplicate elements. List in Java allows duplicates while Set does not allow any duplicate.

    If you insert duplicate in Set it will replace the older value. Any implementation of Set in Java only contains unique elements.

  2. Another significant difference between List and Set in Java is order.

    List is an Ordered Collection while Set is an unordered Collection. List maintains insertion order of elements, means any element which is inserted before will go on lower index than any element which is inserted after.

    Set in Java does not maintain any order. Though Set provide another alternative called SortedSet which can store Set elements in specific Sorting order defined by Comparable and Comparator methods of Objects stored in Set.

  3. Popular implementation of List interface in Java includes ArrayList, Vector and LinkedList.

    Popular implementation of Set interface includes HashSet, TreeSet and LinkedHashSet.

  4. List allows any number of null values. Set can have only a single null value at most.
  5. ListIterator can be used to traverse a List in both the directions(forward and backward). However, it cannot be used to traverse a Set. We can use Iterator (it works with List too) to traverse a Set.
  6. List interface has one legacy class called Vector, whereas Set interface has no legacy class.
  7. When to use Set and when to use List?

    The usage is purely requirement dependent:

    If the requirement is to have only unique values then Set is your best bet as any implementation of Set maintains unique values only.

    If there is a need to maintain the insertion order irrespective of the duplicity then List is the right option.

Hope you have enjoyed reading Difference between Set and List in Java. Please do write us if you have any suggestion/comment or come across any error on this page. Thank you for reading!



Share this page on WhatsApp

Get Free Tutorials by Email

About the Author

is the founder and main contributor for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.