Why does Set.of disallow duplicate elements?

Dave Franken dfranken.jdk at gmail.com
Sun Jan 31 12:54:44 UTC 2021

Okay, I understand this reasoning, but when you want to construct a Set
from an array, you might be tempted to use Set.of(...) because it looks
like it supports an array and indeed, you can do Set.of(new int[] {1, 2 })
I believe?

Maybe this is just a quirk because of how varargs work.

I wondered if there was a canonical way to create a Set from an array, but
couldn't find it, maybe I am missing something?
I did notice Arrays.asList exists (which makes sense because it creates an
ArrayList backed by the array), but not Arrays.asSet.

So the way I would create a Set from an array would be either
Arrays.stream(myArr).collect(Collectors.toUnmodifiableSet()) or new
HashSet<>(Arrays.asList(myArray)) or Set.copyOf(Arrays.asList(myArray)).

I'm not saying the way it is currently implemented is wrong, it's just
something which can suprise developers as it surprised me. :)

Kind regards,


Op za 30 jan. 2021 om 21:30 schreef Remi Forax <forax at univ-mlv.fr>:

> Set.of() is the closest way we've got to a literal Set without having
> introduced a special syntax for that in the language.
> The idea is that if you conceptually want to write
>   Set<String> set = { "hello", "world" };
> instead, you write
>   Set<String> set = Set.of("hello", "world");
> In that context, it makes sense to reject Set constructed with the same
> element twice because this is usually a programming error.
> So
>   Set.of("hello", "hello")
> throws an IAE.
> If you want a Set from a collection of elements, you can use
>   Set.copyOf(List.of("hello", "hello"))
> regards,
> Rémi
> ----- Mail original -----
> > De: "dfranken jdk" <dfranken.jdk at gmail.com>
> > À: "core-libs-dev" <core-libs-dev at openjdk.java.net>
> > Envoyé: Samedi 30 Janvier 2021 19:30:06
> > Objet: Why does Set.of disallow duplicate elements?
> > Dear users,
> >
> > While looking at the implementation of Set.of(...) I noticed that
> > duplicate elements are not allowed, e.g. Set.of(1, 1) will throw an
> > IllegalArgumentException. Why has it been decided to do this?
> >
> > My expectation was that duplicates would simply be removed.
> >
> > If I do for instance new HashSet<>(<collection containing duplicates>)
> > it works and duplicates are removed. To me, it looks a bit inconsistent
> > to have duplicates removed for a collection passed in the constructor,
> > but not for a collection (even though it is a vararg array) passed to a
> > static factory method.
> >
> > Kind regards,
> >
> > Dave Franken

More information about the core-libs-dev mailing list