HashSet & TreeSet in Java
Both HashSet and TreeSet, from java.util, store a collection of unique elements — adding a duplicate simply has no effect, since a Set can never contain the same element twice. They differ in ordering and performance: HashSet offers no guaranteed order at all but constant-time add, remove, and contains checks on average, while TreeSet keeps its elements sorted at all times, at the cost of logarithmic-time operations instead.
TreeSet's sorting relies on either the elements' natural ordering (via Comparable, which built-in types like String and Integer already implement) or an explicit Comparator supplied when the TreeSet is created. Uniqueness itself is determined by equals() for HashSet, or by that same ordering comparison for TreeSet.
Sets store unique elements
Adding a value already present has no effect; a Set never holds duplicates.
HashSet
Offers no guaranteed iteration order, but constant-time add, remove, and contains on average.
TreeSet
Keeps elements sorted at all times, using either their natural ordering or a supplied Comparator, at logarithmic-time cost per operation.
Uniqueness is determined differently
HashSet uses equals() and hashCode() to detect duplicates; TreeSet uses its ordering comparison instead.
Choosing between them
Reach for HashSet when order doesn't matter and speed does; reach for TreeSet when elements need to stay sorted automatically.
import java.util.HashSet;import java.util.TreeSet; public class SetDemo { public static void main(String[] args) { HashSet<Integer> hashSet = new HashSet<>(); hashSet.add(3); hashSet.add(1); hashSet.add(3); TreeSet<Integer> treeSet = new TreeSet<>(hashSet); System.out.println("HashSet size: " + hashSet.size()); System.out.println("Sorted: " + treeSet); }}HashSet trades away any ordering guarantee for speed; TreeSet keeps a sorted structure at all times, which is what its logarithmic cost per operation pays for.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.