In This post we will talk about Difference between List and Set in Java Collection and When to use Set and When to use List Collection?
Both List and Set hold collection of Objects but there are some differences List allows duplicates while Set doesn’t allow duplicate elements. All the elements of a Set must be unique if you try to insert the duplicate element in Set it would replace the existing value from newly added one with same value.
Set is an unordered Collection it doesn’t maintain any insertion order except one implementation of Set which maintains the insertion order that is LinkedHashSet
List collection allows any number of null values but 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 to traverse a both List and Set.
List interface has one legacy class is called Vector whereas Set interface does not have any legacy class
When to use Set and When to use List Collection?
The usage is these collections purely depending on the requirement:
If the requirement is to have only unique collection of values then Set is your best candidate as any implementation of Set maintains unique values only.
If you have requirement that there is a need to maintain the insertion order irrespective of the duplicity then List is a best option
When should we choose LinkedList over ArrayList for a given Scenario and Why?
Is there concurrent version for TreeMap and TreeSet in Java Collections Framework?
What is difference between Collections. Sort() and Arrays.sort()? Which one is better with respect to time efficiency?
What are fail-fast and fail-safe Iterator?
What is difference between Iterator and LisIterator?
Why Prime Numbers are considered in writing certain algorithms like hashcode()?
What all collections utilizes hashCode() method in java?
Describe CopyOnWriteArrayList? Where is it used in Java Applications?
That’s all about When Difference between List and Set in Java Collection ?
If you have any feedback or suggestion please feel free to drop in blow comment box.