Sub topic 9
Unique Elements with Set and HashSet
Some data should never contain repeats. A guest list, the tags on a blog post, and the usernames already taken all have this rule. You could use a List and check for duplicates yourself, but Java has a collection built for the job. This chapter shows you how to use it.
What a Set Is
A Set is a collection that holds each element at most once. Set is an interface, which means it describes what a set can do but does not say how it stores the data. Classes that implement the interface do the actual storing.
A set has two main rules:
- No duplicates. Adding an element that is already there changes nothing.
- No positions. A set has no index, so there is no
get(0)and noset(1, x). You ask whether an element is in the set, not where it is.
The most common implementation is HashSet, a class that stores elements using their hash codes. A hash code is a number that an object's hashCode method returns. You learned about hashCode in the previous chapter. HashSet uses it to find elements fast.
Here is how a set compares with the List you already know:
| Feature | List (ArrayList) | Set (HashSet) |
|---|---|---|
| Duplicates allowed | Yes | No |
| Access by index | Yes, with `get(i)` | No |
| Keeps insertion order | Yes | No guaranteed order |
| Speed of `contains` | Slow for big lists (checks each item) | Fast, even for big sets |
| Typical use | A sequence of items | A group of distinct items |
Your First HashSet
You declare a set the same way you declare a list. Put the interface type on the left and the class on the right, and use the diamond operator <>.
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
System.out.println(tags.remove("java")); // true
System.out.println(tags.remove("java")); // false, not there anymore
System.out.println(tags.isEmpty()); // false
}
}Look closely at add. It returns a boolean, which is a true-or-false value. It returns true when the element was new and got added. It returns false when the element was already in the set. remove works the same way: true if something was removed, false if the element was not there.
Here is that trick in action. The program finds the first repeated word:
import java.util.HashSet;
import java.util.Set;
public class FirstRepeat {
public static void main(String[] args) {
String[] words = {"red", "blue", "green", "blue", "red"};
Set<String> seen = new HashSet<>();
for (String w : words) {
if (!seen.add(w)) {
System.out.println("First repeat: " + w); // First repeat: blue
break;
}
}
}
}Removing Duplicates from a List
A very common task is cleaning duplicates out of a list. You can pass any collection to the HashSet constructor, and the set keeps one copy of each element.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class DedupDemo {
public static void main(String[] args) {
List<String> visitors = List.of("ana", "ben", "ana", "cara", "ben");
Set<String> unique = new HashSet<>(visitors);
System.out.println(unique.size()); // 3
System.out.println(unique.contains("cara")); // true
List<String> cleaned = new ArrayList<>(unique);
System.out.println(cleaned.size()); // 3
}
}If you need a list again, pass the set to the ArrayList constructor, as the last lines show.
How HashSet Finds Elements
HashSet is fast because it does not check every element. Inside, it keeps an array of buckets. A bucket is a small slot that holds the elements whose hash codes point to it. When you call add(x):
- HashSet calls
x.hashCode()and uses the number to pick a bucket. - It looks only at the elements in that bucket.
- For each one, it calls
equalsto see if it matchesx. - If one matches,
addreturnsfalse. If none match, it storesxand returnstrue.
contains and remove follow the same steps. Because each bucket usually holds just zero or one element, these operations take about the same time whether the set has 10 elements or 10 million. Programmers call this constant time.
This is why the previous chapter's rules matter. If two equal objects returned different hash codes, they would land in different buckets. HashSet would never compare them, and you would get "duplicates" in your set.
Combining Sets: Union, Intersection, Difference
Sets support three classic operations from math. Each is a method that changes the set you call it on.
| Operation | Method | Result keeps |
|---|---|---|
| Union | `a.addAll(b)` | Everything in a or b |
| Intersection | `a.retainAll(b)` | Only things in both a and b |
| Difference | `a.removeAll(b)` | Things in a but not in b |
Since these methods change a, you should copy it first if you still need the original.
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class SetMath {
public static void main(String[] args) {
Set<Integer> a = new HashSet<>(List.of(1, 2, 3, 4));
Set<Integer> b = new HashSet<>(List.of(3, 4, 5));
Set<Integer> union = new HashSet<>(a);
union.addAll(b);
System.out.println(union.size()); // 5
Set<Integer> both = new HashSet<>(a);
both.retainAll(b);
System.out.println(both.contains(3)); // true
System.out.println(both.size()); // 2
Set<Integer> onlyA = new HashSet<>(a);
onlyA.removeAll(b);
System.out.println(onlyA.contains(1)); // true
System.out.println(onlyA.contains(3)); // false
System.out.println(a.size()); // 4, a is unchanged
}
}Looping Over a Set
You cannot use an index, but a for-each loop works just like it does with a list:
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class SetLoop {
public static void main(String[] args) {
Set<String> colors = new HashSet<>(List.of("red", "green", "blue"));
int totalLetters = 0;
for (String c : colors) {
totalLetters += c.length();
}
System.out.println(totalLetters); // 12
}
}The same safety rule from the iteration chapters applies. Do not call colors.remove(...) inside a for-each loop. Use Iterator.remove or colors.removeIf(...) instead.
Edge Cases and Common Mistakes
Changing an object after adding it
If you change a field that hashCode uses after the object is already in a set, the set loses track of it. The object stays in its old bucket, but lookups now search a different one.
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class MutableTrap {
static class Tag {
String name;
Tag(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
return o instanceof Tag && ((Tag) o).name.equals(name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
}
public static void main(String[] args) {
Set<Tag> tags = new HashSet<>();
Tag t = new Tag("java");
tags.add(t);
t.name = "python"; // changes the hash code
System.out.println(tags.contains(t)); // false
System.out.println(tags.size()); // 1, it is still in there
}
}Other things to know
- null is allowed once. A HashSet can hold a single
nullelement. Most code is clearer if you avoid it. - Forgetting equals and hashCode. If your own class does not override them, two objects with the same fields count as different, and both get stored.
- Expecting
get. There is nogeton a set. Usecontainsto test membership, or loop to visit every element.
Exercise
What does this code print? Set<String> s = new HashSet<>(); s.add("a"); s.add("b"); System.out.println(s.add("a") + " " + s.size());
Show answer
It prints "false 2". The second add("a") returns false because "a" is already in the set, and the set still holds only "a" and "b".
Exercise
You have List<Integer> scores = List.of(90, 75, 90, 60, 75). Write one line that tells you how many distinct scores there are.
Show answer
System.out.println(new HashSet<>(scores).size()); prints 3, because the set keeps one copy each of 90, 75, and 60.
Exercise
Sets a = {1, 2, 3} and b = {2, 3, 4} are both HashSets. After running a.retainAll(b), what does a contain, and what happened to the original contents of a?
Show answer
a now contains 2 and 3 (in no guaranteed order). The original a is gone, because retainAll changes the set it is called on. To keep the original, copy it first with new HashSet<>(a).
Exercise
A Person class overrides equals to compare names but does not override hashCode. You add new Person("Ana") twice to a HashSet. Why might the size be 2?
Show answer
Without hashCode, each object uses the default hash code, which usually differs for separate objects. The two Ana objects land in different buckets, so HashSet never calls equals on them and stores both.