diff --git a/libs/core/src/main/java/org/elasticsearch/core/List.java b/libs/core/src/main/java/org/elasticsearch/core/List.java index 325405f945a72..ba8843dfd6ec3 100644 --- a/libs/core/src/main/java/org/elasticsearch/core/List.java +++ b/libs/core/src/main/java/org/elasticsearch/core/List.java @@ -8,6 +8,7 @@ package org.elasticsearch.core; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; @@ -75,8 +76,14 @@ public static java.util.List of(T... entries) { * @param coll a {@code Collection} from which elements are drawn, must be non-null * @return a {@code List} containing the elements of the given {@code Collection} */ - @SuppressWarnings("unchecked") public static java.util.List copyOf(Collection coll) { - return (java.util.List) List.of(coll.toArray()); + switch (coll.size()) { + case 0: + return Collections.emptyList(); + case 1: + return Collections.singletonList(coll.iterator().next()); + default: + return Collections.unmodifiableList(new ArrayList<>(coll)); + } } } diff --git a/libs/core/src/main/java/org/elasticsearch/core/Set.java b/libs/core/src/main/java/org/elasticsearch/core/Set.java index 7fca623126247..003ce934aa68c 100644 --- a/libs/core/src/main/java/org/elasticsearch/core/Set.java +++ b/libs/core/src/main/java/org/elasticsearch/core/Set.java @@ -61,9 +61,9 @@ public static java.util.Set of(T e1, T e2) { public static java.util.Set of(T... entries) { switch (entries.length) { case 0: - return Set.of(); + return of(); case 1: - return Set.of(entries[0]); + return of(entries[0]); default: return Collections.unmodifiableSet(new HashSet<>(Arrays.asList(entries))); } @@ -78,8 +78,14 @@ public static java.util.Set of(T... entries) { * @throws NullPointerException if coll is null, or if it contains any nulls * @since 10 */ - @SuppressWarnings("unchecked") public static java.util.Set copyOf(Collection coll) { - return (java.util.Set) Set.of(new HashSet<>(coll).toArray()); + switch (coll.size()) { + case 0: + return Collections.emptySet(); + case 1: + return Collections.singleton(coll.iterator().next()); + default: + return Collections.unmodifiableSet(new HashSet<>(coll)); + } } }