Set<E>
- Java course
- Intermediate
- Lesson 90/116
- 5 min
Learn generic sets with Set<E>.
The Set<E> interface
Set<E> is a collection of unique elements; you cannot add the same element twice. The most common concrete implementation is HashSet: Set<String> tags = new HashSet<>();.
The add(e) method adds the element if absent and returns true; if already present it skips and returns false. contains(e) checks membership. Set does not guarantee insertion order; use LinkedHashSet when order matters.
Removing duplicates with a Set
The most common use of a Set is removing duplicates. Building a Set from a list keeps one copy of each: Set<String> unique = new HashSet<>(listWithDuplicates);. The set's size() gives the unique count.
remove(e) deletes an element; clear() empties the set; isEmpty() checks emptiness. For intersection use retainAll; for union use addAll.
Practice Build a tag set
Declare Set<String> tags = new HashSet<>();. Call tags.add("java");, tags.add("code"); and tags.add("java"); (the third is a duplicate). Print the unique count with System.out.println(tags.size()); and the membership of code with System.out.println(tags.contains("code"));.
Starter code
import java.util.Set;
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
// Declare Set<String>, three add (one duplicate), print size and contains
}
}Sample solution
import java.util.Set;
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
Set<String> tags = new HashSet<>();
tags.add("java");
tags.add("code");
tags.add("java");
System.out.println(tags.size());
System.out.println(tags.contains("code"));
}
}Expected output
2 true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens if tags.add("Java") is called twice?
- The second call throws an error
- Two Java elements appear in the set
- The set becomes empty
- First add stays, second returns false Correct answer
Explanation: A Set is unique; the second add returns false and adds nothing.
2 Match the Set methods
| Term | Meaning |
|---|---|
add(e) |
Adds if unique |
contains(e) |
Checks membership |
remove(e) |
Deletes an element |
size() |
Number of unique elements |
3 Complete the Set declaration
Set<String> tags = new ____<>();
Set<String> tags = new HashSet<>();
Explanation: HashSet is the common concrete implementation of Set.