Collections with no duplicates. HashSet is fastest; TreeSet keeps items sorted.
Java · intermediate · 6 min · 11 steps · free
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class SetsDemo {
public static void main(String[] args) {
Set<Integer> seen = new HashSet<>();
boolean added1 = seen.add(42);
boolean added2 = seen.add(42); // already there: add returns false
seen.add(7);
Set<String> sorted = new TreeSet<>(); // keeps items in sorted order
sorted.add("pear");
sorted.add("apple");
sorted.add("fig");
String firstWord = ((TreeSet<String>) sorted).first();
System.out.println(added1 + " " + added2 + " " + seen.size() + " " + sorted + " " + firstWord);
}
}main. args holds its command-line arguments (none here). seen is created on the stack and points to a new HashSet on the heap: [].seen points to, index 0 changes from 42 to 7 and index 1 changes from null to 42.sorted.add("pear").sorted.add("apple").sorted.add("fig").true false 2 [apple, fig, pear] apple.Answer: [1, 2, 3]. TreeSet sorts.
Answer: x was already in the set. Duplicates are rejected.
← HashMap: Look Up by Key · Iterators: Removing While Looping →