Difference between HashSet and TreeSet
Feature | HashSet | TreeSet |
Definition | HashSet is an implementation of the Set interface. It stores unique elements (no duplicates). | TreeSet is an ordered version of HashSet. It maintains the insertion order of elements. |
Duplicates | HashSet does not allow duplicate elements. | TreeSet also does not allow duplicate elements. |
Ordering | HashSet does not maintain any specific order of elements. | TreeSet maintains the insertion order of elements. |
Null Values | HashSet allows a single null value. | TreeSet allows a single null value. |
Implementation | HashSet uses a hash table for storage. | TreeSet uses a balanced binary search tree (usually a red-black tree) for storage. |
Example | java Set<String> names = new HashSet<>(); names.add(“Alice”); names.add(“Bob”); names.add(“Charlie”); System.out.println(names); | java Set<String> names = new TreeSet<>(); names.add(“Alice”); names.add(“Bob”); names.add(“Charlie”); System.out.println(names); |
Table of Contents
In the examples above, HashSet stores unique names, while TreeSet maintains the insertion order of names. Remember that HashSet is ideal for maintaining a collection of unique elements, while TreeSet is useful when order matters.