Java Choose What Uniqueness and Order Mean
A set prevents duplicates according to its equality or comparison rules. The kind of set determines whether iteration order is unspecified, insertion-based or sorted.
Understand the idea
HashSet uses equals and hashCode and does not promise a useful iteration order. LinkedHashSet retains encounter order for its normal insertion-based use. TreeSet uses an ordering comparison; values comparing as zero are treated as the same set position. Select this policy deliberately, especially when a comparator ignores part of an object’s state.
Run it locally
Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.
javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out MainA worked example
import java.util.Set;
import java.util.LinkedHashSet;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
Set<String> encounter = new LinkedHashSet<>();
encounter.add("Wood");
encounter.add("Clay");
encounter.add("Wood");
Set<String> sorted = new TreeSet<>(encounter);
System.out.println(encounter);
System.out.println(sorted);
}
}
Expected output
[Wood, Clay]
[Clay, Wood]The duplicate Wood does not add another entry. The first result retains arrival order; the second follows the strings’ natural order. If the task needs locale-sensitive human text order, natural String ordering is not automatically the right comparison. Set membership can be useful without printing or depending on the full traversal order.
Check the official Java documentation for detailed contracts and supported options.