Sets: HashSet and TreeSet

Collections with no duplicates. HashSet is fastest; TreeSet keeps items sorted.

Java · intermediate · 6 min · 11 steps · free

What you'll learn

SetsDemo.java

import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

public class SetsDemo {
    public static void main(String[] args) {
        Set<Integer> seen = new HashSet<>();
        boolean added1 = seen.add(42);
        boolean added2 = seen.add(42);          // already there: add returns false
        seen.add(7);
        Set<String> sorted = new TreeSet<>();   // keeps items in sorted order
        sorted.add("pear");
        sorted.add("apple");
        sorted.add("fig");
        String firstWord = ((TreeSet<String>) sorted).first();
        System.out.println(added1 + " " + added2 + " " + seen.size() + " " + sorted + " " + firstWord);
    }
}

Step by step

  1. The program starts in main. args holds its command-line arguments (none here). seen is created on the stack and points to a new HashSet on the heap: [].
  2. add returns true: 42 was new.
  3. Adding 42 again returns false: sets keep each value once.
  4. In the HashSet that seen points to, index 0 changes from 42 to 7 and index 1 changes from null to 42.
  5. A TreeSet keeps its items sorted, whatever order they are added in.
  6. Line runs: sorted.add("pear").
  7. Line runs: sorted.add("apple").
  8. Line runs: sorted.add("fig").
  9. first() gives the smallest: "apple".
  10. It prints true false 2 [apple, fig, pear] apple.
  11. true, false, 2, [apple, fig, pear] and apple.

Common mistakes

Best practices

Key takeaways

Check yourself

TreeSet with 3, 1, 2 prints as?

Answer: [1, 2, 3]. TreeSet sorts.

set.add(x) returns false when?

Answer: x was already in the set. Duplicates are rejected.

·

More in The Collections Framework