Collections: Set.copyOf silently drops duplicates that Set.of rejects

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.

Code
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());
}
Output
Set.copyOf size (duplicates dropped): 3
Set.of throws on duplicates: IllegalArgumentException
Advertisement
More in JAVA

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

© Java Coding Hub · About · Contact · Privacy · Terms