List
and Set
are two important Java Collection
classes. The most important differerences between them are:
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.
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
.
List
interface in Java includes ArrayList
, Vector
and LinkedList
.
Popular implementation of Set
interface includes HashSet
, TreeSet
and LinkedHashSet
.
null
values. Set
can have only a single null
value at most.
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
.
Vector
, whereas Set
interface has no legacy class. 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