Member-only story
InterView: How Set Prevent Duplicates Internally in Java
6 min readDec 28, 2024
In Java, a Set is a collection that:
- Does not allow duplicate elements.
- Does not maintain any particular order, except for specific implementations like
LinkedHashSet
orTreeSet
The Set interface is a part of the Java Collections Framework and extends the Collection interface
Common Implementations of Set
1.HashSet
- Does not maintain any specific order of elements.
- Backed by a hash table.
- Provides constant-time performance for basic operations (like add, remove, and contains)
if you are not a medium member then Click here to read free
Set<String> hashSet = new HashSet<>();
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Apple"); // Duplicate, won't be added
System.out.println(hashSet); // Output: [Apple, Banana]
2.LinkedHashSet
- Maintains the order of elements as they are inserted.
- Slightly slower than
HashSet
because of the additional overhead of maintaining insertion order
Set<String> linkedHashSet = new LinkedHashSet<>()…