A Set stores at most one entry for each equal value. Use it when membership matters more than repeated occurrences. LinkedHashSet keeps insertion order, making a first-seen report predictable. HashSet does not promise that order; never infer a guarantee from one observed printout.
Work through the example
add returns true when membership changes and false for an existing value. contains asks a membership question without adding anything. LinkedHashSet uses equals and hashCode together, which is why yesterday's value contract matters.
A set removes duplicates according to equality, not according to what a human thinks looks similar. "Java" and "java" remain different strings unless the application deliberately normalizes them. Keep normalization at the boundary and tell users the policy. A task ID should usually retain an explicit, stable form.
Before Run, write the output and identify the exact line responsible for each result. Each editor is a separate program; names and edits in one box do not carry into the next.
import java.util.Set;
import java.util.LinkedHashSet;
public class Main {
public static void main(String[] args) {
Set<String> topics = new LinkedHashSet<>();
System.out.println(topics.add("Java"));
System.out.println(topics.add("Loops"));
System.out.println(topics.add("Java"));
System.out.println(topics.contains("java"));
System.out.println(topics);
}
}Check your prediction
true
true
false
false
[Java, Loops]Compare the behavior
A set can summarize first occurrences without destroying the original list. Constructing it from a list reads the list in order. Do not convert to a set if repeated events carry information: three identical study sessions may represent three real sessions. Choose the structure after describing what a duplicate means.
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.LinkedHashSet;
public class Main {
public static void main(String[] args) {
List<String> visits = new ArrayList<>();
visits.add("Java");
visits.add("Java");
visits.add("Tests");
Set<String> unique = new LinkedHashSet<>(visits);
System.out.println(visits.size());
System.out.println(unique.size());
System.out.println(unique);
}
}Check your prediction
3
2
[Java, Tests]Connect uniqueness to the equality contract
A set does not count occurrences. After adding Java three times, the set still has one equal value; the original event list may still have three meaningful visits. Decide whether the question is “how many events?” or “which values occurred?” before converting containers.
For custom objects, the set uses exactly the equals and hashCode you write. Yesterday's lesson said to write them as a pair. Here is what happens when only equals is written: predict the three lines before running.
import java.util.Set;
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
Set<Key> keys = new HashSet<>();
keys.add(new Key("T-1"));
keys.add(new Key("T-1"));
System.out.println(new Key("T-1").equals(new Key("T-1")));
System.out.println(keys.size());
System.out.println(keys.contains(new Key("T-1")));
}
}
final class Key {
private final String code;
Key(String code) {
this.code = code;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof Key)) {
return false;
}
Key key = (Key) other;
return code.equals(key.code);
}
}Check your prediction
true
2
falseThe two keys are equal, yet the set holds both and cannot find a third. A hash set first uses hashCode to pick where to look, and only compares with equals among entries with the same hash code. Without an override, hashCode comes from Object and is different for each object, so the set never even calls equals. Now fix it: add
@Override
public int hashCode() {
return code.hashCode();
}to Key and run again. The output becomes true, 1, true. The rule is: equal
objects must have equal hash codes.
LinkedHashSet keeps the first insertion position of an equal value. Re-adding an existing entry does not move it to the end. Trace Read, Test, Read, Walk to obtain Read, Test, Walk. Then add a differently cased spelling and predict whether it is equal under your normalization policy. Preserve the source when repeated events still matter elsewhere.
Practice independently
Set & Uniqueness: practice
Write uniqueNonblank(String[] labels) that trims each nonnull label, skips blank results, and returns a LinkedHashSet in first-seen order. Null elements are outside this exercise's contract. For {" Java ", "", "Java", "Tests"}, print [Java, Tests]. For an empty array, print [].
Spend a few minutes on your own first. Compile after one small change, read the first error, and check the result against the requirements rather than matching the solution's layout.
import java.util.Set;
import java.util.LinkedHashSet;
public class Main {
public static void main(String[] args) {
System.out.println("Implement uniqueNonblank");
}
}Hint 1: the idea
Normalize before testing membership; otherwise two spellings can enter separately.
Hint 2: a first step
Trim into a local variable and add it only when it is not empty.
Show one solution
One possible implementation follows. Compare its decisions with yours: which values can change, what inputs are accepted, and what would expose a mistake?
import java.util.Set;
import java.util.LinkedHashSet;
public class Main {
public static void main(String[] args) {
System.out.println(uniqueNonblank(new String[] {" Java ", "", "Java", "Tests"}));
System.out.println(uniqueNonblank(new String[0]));
}
static Set<String> uniqueNonblank(String[] labels) {
Set<String> result = new LinkedHashSet<>();
for (String label : labels) {
String normalized = label.trim();
if (!normalized.isEmpty()) {
result.add(normalized);
}
}
return result;
}
}Expected output:
[Java, Tests]
[]Change it and test again
Add lowercase "java" and predict the result before running. Then change the requirement to case-insensitive labels and describe how you would preserve a display spelling. Do not introduce lowercasing silently into identifiers whose case may matter.
Explain before moving on
What information would be lost by replacing a visit list with a set? Why must equal custom objects have equal hash codes?
Completion is saved in this browser only. It does not measure mastery.