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

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


Hi Tagir,
> 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.

You are right. I haven't thought about this cases. OK, then we should
at least add an optimisation for the case where coll is an instance of
HashSet:

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 HashSet<?>) {
+            return (Set<E>)Set.of(coll.toArray());
         } else {
             return (Set<E>)Set.of(new HashSet<>(coll).toArray());
         }



Best regards,
Andrej Golovnin


More information about the core-libs-dev mailing list