Understanding HashSet, LinkedHashSet, and TreeSet in Java
Saeed Anabtawi
Founder @ interview.ps | Mentor @GazaSkyGeeks | Content Creator @ CodeWithSaeed
HashSet, LinkedHashSet, and TreeSet in Java are commonly used classes that implement the Set interface from the Java Collections Framework. They are used for storing unique elements – in other words, they do not allow duplicates. However, they each have different characteristics and use cases. Let's look into each of these Set implementations and understand when to use which, complemented by examples.
HashSet
HashSet is the most common Set implementation. It stores elements in a hash table, which allows for fast execution times for basic operations, like add, remove, contains and size.
Key features of HashSet:
Example of using HashSet:
java
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> hSet = new HashSet<String>();
hSet.add("Apple");
hSet.add("Banana");
hSet.add("Cherry");
hSet.add("Apple"); // This will not be added as "Apple" is already present in the set
System.out.println("HashSet: " + hSet); // Output order may vary
}
}
LinkedHashSet
LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order).
Key features of LinkedHashSet:
Example of using LinkedHashSet:
java
import java.util.LinkedHashSet;
public class Main {
public static void main(String[] args) {
LinkedHashSet<String> lhSet = new LinkedHashSet<String>();
lhSet.add("Apple");
lhSet.add("Banana");
lhSet.add("Cherry");
System.out.println("LinkedHashSet: " + lhSet); // Output will maintain insertion order
}
}
TreeSet
TreeSet is a NavigableSet implementation that uses a Tree for storage. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.
Key features of TreeSet:
Example of using TreeSet:
java
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
TreeSet<String> tSet = new TreeSet<String>();
tSet.add("Apple");
tSet.add("Banana");
tSet.add("Cherry");
System.out.println("TreeSet: " + tSet); // Output will be in sorted order
}
}
When to Use HashSet, LinkedHashSet, or TreeSet
The choice between HashSet, LinkedHashSet, and TreeSet should depend on your specific requirements:
Use HashSet when:
Use LinkedHashSet when:
Use TreeSet when:
Always choose the right Set implementation based on your specific needs and performance requirements. Experiment and benchmark if you are unsure about the performance implications of your choice.