Sunday, September 21, 2014

Difference between List and Set in Java Collection

         Both List and Set are two of most important Collection classes Java Program use along with various Map implementation. Basic feature of List and Set are abstracted in List and Set interface in Java and then various implementation of List and Set adds specific feature on top of that e.g. ArrayList in Java is a List implementation backed by Array while LinkedList is another List implementation which works like linked list data-structure.

List vs Set in Java

  1. Fundamental difference between List and Set in Java is allowing duplicate elements. List in Java allows duplicates while Set doesn't allow any duplicate. If you insert duplicate in Set it will replace the older value. Any implementation of Set in Java will only contains unique elements.

  2. List allows null elements and you can have many null objects in a List, because it also allowed duplicates. Set just allow one null element as there is no duplicate permitted.

  3.  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 doesn't  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.Set uses equals() method to check uniqueness of elements stored in Set, while SortedSet uses compareTo() method to implement natural sorting order of elements. In order for an element to behave properly in Set and SortedSet, equals and compareTo must be consistent to each other.
  4. Popular implementation of List interface in Java includes ArrayList, Vector and LinkedList. While popular implementation of Set interface includes HashSet, TreeSet and LinkedHashSet.

When to use List and Set in Java

Another good follow-up question is "when do you use List and Set in Java" , which can also be answered based on properties of List and Set we have learn here.These difference between Set and List also teaches us when to use Set and when to prefer List. its pretty clear that if you need to maintain insertion order or object and you collection can contain duplicates than List is a way to go. On the other hand if your requirement is to maintain unique collection without any duplicates than Set is the way to go.
Important point to note is that both List and Set are derived from Collection Interface. In short main difference between List and Set in Java is that List is an ordered collection which allows duplicates while Set is an unordered collection which doesn't allow duplicates.

No comments:

Post a Comment