Sub topic 9
Unique Elements with Set and HashSet
A list lets you store the same value many times. Sometimes you want each value only once, such as the tags on a blog post or the email addresses on a mailing list. A Java Set handles that.
What a Set Is
A Set is a collection that holds each element at most once. If you add a value that is already there, the set stays the same. Set is an interface, so it describes what a set can do but does not store anything by itself.
A HashSet is the most common class that implements Set. It uses a technique called hashing to find elements quickly. Hashing turns an object into a number, called a hash code, which tells the set where to look for that object.
Two things make a set different from a list:
- A set has no duplicates.
- A set has no index. You cannot call
get(0)on a set.
Adding and Checking Elements
The add method returns a boolean. It returns true when the element was new and false when the element was already in the set.
import java.util.HashSet;
import java.util.Set;
public class SetDemo {
public static void main(String[] args) {
Set<String> tags = new HashSet<>();
System.out.println(tags.add("java")); // true
System.out.println(tags.add("java")); // false, already present
tags.add("collections");
System.out.println(tags.size()); // 2
System.out.println(tags.contains("java")); // true
}
}The contains method checks whether a value is in the set. On a HashSet this check is fast, even when the set holds millions of elements. Checking a large ArrayList is slower, because the list compares the value with each element in turn.
Removing Duplicates from a List
A common task is to remove duplicates from a list. You can pass the list straight to the HashSet constructor.
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class DedupeDemo {
public static void main(String[] args) {
List<String> emails = List.of("[email protected]", "[email protected]", "[email protected]", "[email protected]");
Set<String> unique = new HashSet<>(emails);
System.out.println(emails.size()); // 4
System.out.println(unique.size()); // 3
System.out.println(unique.contains("[email protected]")); // true
unique.remove("[email protected]");
System.out.println(unique.size()); // 2
}
}The remove method deletes a value from the set. It returns true if the value was there.
Sets of Your Own Objects
For strings and numbers, HashSet already knows when two values are equal. For your own classes, the set uses the equals and hashCode methods to decide. If you do not override both of them, two objects with the same fields count as different elements. The chapter "How Java Decides Two Objects Are Equal" shows how to write these methods correctly.
Common Set Methods
| Method | What it does | Returns |
|---|---|---|
| `add(e)` | Adds `e` if it is not already present | `true` if added |
| `contains(e)` | Checks whether `e` is in the set | `true` if found |
| `remove(e)` | Deletes `e` | `true` if removed |
| `size()` | Counts the elements | an `int` |
| `isEmpty()` | Checks whether the set has no elements | `true` if empty |
Exercise
You run Set<Integer> s = new HashSet<>(); s.add(5); s.add(7); s.add(5); and then call s.size(). What is printed if you print the result, and what did the third add call return?
Show answer
The size is 2, because 5 is stored only once. The third add call returned false because 5 was already in the set.
Exercise
Why can't you write tags.get(0) on a Set<String>?
Show answer
A set has no index. The Set interface has no get(int) method, so the code does not compile. Use contains to check for a value, or loop over the set to read its elements.