Set.of throws IllegalArgumentException the moment it sees a duplicate argument, but Set.copyOf(collection) simply collapses duplicate elements from the source collection without complaint.
List<String> withDupes = List.of("a", "b", "a", "c");
Set<String> copy = Set.copyOf(withDupes);
System.out.println("Set.copyOf size (duplicates dropped): " + copy.size());
try {
Set.of("a", "b", "a");
} catch (IllegalArgumentException e) {
System.out.println("Set.of throws on duplicates: " + e.getClass().getSimpleName());
}
Set.copyOf size (duplicates dropped): 3
Set.of throws on duplicates: IllegalArgumentException
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-09-27