[PATCH] Minor optimisation for Set.copyOf(Collection)

Andrej Golovnin andrej.golovnin at gmail.com
Fri Jun 22 09:42:21 UTC 2018


> 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