Set in Java
Set is a collection interface for elements that should not appear more than once. Adding an element that is already present does not create another entry. A set has no indexed get operation like a list.
Why Do We Need This?
Suppose we record which topics a learner has completed. Completing Arrays twice should not count as two different completed topics. A set helps keep one entry for each topic.
Main Ideas
| Concept | What it means |
|---|---|
| add(value) | Returns false if the set already contains an equivalent element |
| contains(value) | Checks whether an element is present |
| HashSet | Does not promise an iteration order |
| LinkedHashSet | Normally keeps insertion order |
| TreeSet | Keeps a sorted order using natural ordering or a comparator |
Simple Working Example
Run this program on its own. All required imports and classes are included.
import java.util.LinkedHashSet;
import java.util.Set;
public class HelloWorld {
public static void main(String[] args) {
Set<String> completed = new LinkedHashSet<>();
completed.add("Arrays");
completed.add("Strings");
boolean addedAgain = completed.add("Arrays");
System.out.println(completed);
System.out.println("Added again: " + addedAgain);
}
}Output
[Arrays, Strings]
Added again: falseLinkedHashSet makes the shown iteration order predictable. Hash-based sets use equals and hashCode to identify equal elements. A TreeSet uses its ordering comparison, so that comparison should be consistent with equals to follow the general Set contract.
Topics in This Section
Easy Way to Remember
A set expresses uniqueness. Choose its implementation according to the ordering and lookup behavior you need.
See you in next page....??