Did you know Set.of does that?

I was working on some code and need to turn an array into a set. I knew that Set.of() has a varargs overload so I tried to use it. And promptly learned that it doesn’t work for my needs.

How many ways can you think of that set1 and set2 differ here?

String[] words = { "all", "the", "words", "in", "the", "world" };

Set<String> set1 = new HashSet<>(Arrays.asList(words));

Set<String> set2 = Set.of(words);


set2 is immutable while set1 is not. I knew that going in. I don’t need to modify the set I’m creating so that’s fine.


set2 doesn’t get created if there are duplicates in words. set1 does. This is a big difference and caught me by surprise. And what better way to deal with a surprise than make it a blog post? Surprise! (And yes, this in the JavaDoc. So if I had read the exception details in the JavaDoc, I wouldn’t have been surprised.)

Leave a Reply

Your email address will not be published. Required fields are marked *