diff --git a/src/java.base/share/classes/java/util/ImmutableCollections.java b/src/java.base/share/classes/java/util/ImmutableCollections.java index 4c8fd0cfc8f..3de7e1d5eae 100644 --- a/src/java.base/share/classes/java/util/ImmutableCollections.java +++ b/src/java.base/share/classes/java/util/ImmutableCollections.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -166,10 +166,12 @@ class ImmutableCollections { */ @SuppressWarnings("unchecked") static List listCopy(Collection coll) { - if (coll instanceof List12 || (coll instanceof ListN && ! ((ListN)coll).allowNulls)) { + if (coll instanceof List12 || (coll instanceof ListN c && !c.allowNulls)) { return (List)coll; + } else if (coll.isEmpty()) { // implicit nullcheck of coll + return List.of(); } else { - return (List)List.of(coll.toArray()); // implicit nullcheck of coll + return (List)List.of(coll.toArray()); } } diff --git a/src/java.base/share/classes/java/util/Map.java b/src/java.base/share/classes/java/util/Map.java index f20f0a259a9..4e8a2496e2a 100644 --- a/src/java.base/share/classes/java/util/Map.java +++ b/src/java.base/share/classes/java/util/Map.java @@ -1738,6 +1738,8 @@ public interface Map { static Map copyOf(Map map) { if (map instanceof ImmutableCollections.AbstractImmutableMap) { return (Map)map; + } else if (map.isEmpty()) { // Implicit nullcheck of map + return Map.of(); } else { return (Map)Map.ofEntries(map.entrySet().toArray(new Entry[0])); } diff --git a/src/java.base/share/classes/java/util/Set.java b/src/java.base/share/classes/java/util/Set.java index 4c703008a87..5ce3bf04c7c 100644 --- a/src/java.base/share/classes/java/util/Set.java +++ b/src/java.base/share/classes/java/util/Set.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -728,6 +728,8 @@ public interface Set extends Collection { static Set copyOf(Collection coll) { if (coll instanceof ImmutableCollections.AbstractImmutableSet) { return (Set)coll; + } else if (coll.isEmpty()) { // Implicit nullcheck of coll + return Set.of(); } else { return (Set)Set.of(new HashSet<>(coll).toArray()); }