[PATCH] Minor optimisation for Set.copyOf(Collection)
Tagir Valeev
amaembo at gmail.com
Fri Jun 22 10:21:59 UTC 2018
Hello!
What if it's TreeSet with custom comparator which may differentiate
elements equal by .equals()? Or, even simpler,
Collections.newSetFromMap(new IdentityHashMap<>())? In both cases
Set.of(array) would throw.
With best regards,
Tagir Valeev.
On Fri, Jun 22, 2018 at 4:43 PM Andrej Golovnin <andrej.golovnin at gmail.com>
wrote:
> > Hi all,
> >
> > the current implementation of Set.copyOf(Collection<? extends E> coll)
> > creates an intermediate HashSet object to remove duplicates even when
> > coll is already a Set. The attached patch adds an additional check
> > whether coll is already a Set and if yes, then calls #toArray()
> > directly on coll and passes the result to Set.of().
>
> It looks like my patch was stripped. Now inlined:
>
> diff --git a/src/java.base/share/classes/java/util/Set.java
> b/src/java.base/share/classes/java/util/Set.java
> --- a/src/java.base/share/classes/java/util/Set.java
> +++ b/src/java.base/share/classes/java/util/Set.java
> @@ -723,6 +723,8 @@
> static <E> Set<E> copyOf(Collection<? extends E> coll) {
> if (coll instanceof ImmutableCollections.AbstractImmutableSet) {
> return (Set<E>)coll;
> + } else if (coll instanceof Set<?>) {
> + return (Set<E>)Set.of(coll.toArray());
> } else {
> return (Set<E>)Set.of(new HashSet<>(coll).toArray());
> }
>
More information about the core-libs-dev
mailing list