-
CSR
-
Resolution: Unresolved
-
P4
-
None
-
behavioral
-
minimal
-
-
Java API
-
SE
Summary
This change updates the mutator methods on the unmodifiable collection views entrySet()
keySet()
values()
returned by Map.of()
to throw UnsupportedOperationException
.
Problem
<code class="prettyprint" data-shared-secret="1742016133749-0.16320001349096247">Map.of()</code> is specified as returning an unmodifiable collection.
Returns an unmodifiable map containing zero mappings.
The specification for unmodifiable collections requires the mutator methods of unmodifiable collections, and their derived view collections, to throw UnsupportedOperationException
:
An unmodifiable collection is a collection, all of whose mutator methods (as defined above) are specified to throw UnsupportedOperationException. Such a collection thus cannot be modified by calling any methods on it. For a collection to be properly unmodifiable, any view collections derived from it must also be unmodifiable. For example, if a List is unmodifiable, the List returned by List.subList is also unmodifiable.
In JDK 11 and newer, the mutator methods on the unmodifiable set returned by Map.of().entrySet()
do not modify the underlying view, and also do not throw UnsupportedOperationException
. In earlier versions the mutator methods of entrySet()
threw UnsupportedOperationException
. keySet()
or values()
always had the post-11 behaviors of entrySet()
.
Solution
The solution is to make the mutator methods entrySet()
keySet()
values()
of Map.of()
throw UnsupportedOperationException
.
An alternate is to leave the existing behaviors in place, and prioritize compatibility with existing code that may rely on the buggy behaviour over compliance with the specification.
Specification
The specification for unmodifiable maps will be updated to explicitly say that mutator methods on derived view collections will also throw UnsupportedOperationException
:
diff --git a/src/java.base/share/classes/java/util/Map.java b/src/java.base/share/classes/java/util/Map.java
index ea2fd4e1807..6462a54df31 100644
--- a/src/java.base/share/classes/java/util/Map.java
+++ b/src/java.base/share/classes/java/util/Map.java
@@ -122,8 +122,8 @@
*
* <ul>
* <li>They are <a href="Collection.html#unmodifiable"><i>unmodifiable</i></a>. Keys and values
- * cannot be added, removed, or updated. Calling any mutator method on the Map
- * will always cause {@code UnsupportedOperationException} to be thrown.
+ * cannot be added, removed, or updated. Calling any mutator method on the Map or any derived view
+ * collection will always cause {@code UnsupportedOperationException} to be thrown.
* However, if the contained keys or values are themselves mutable, this may cause the
* Map to behave inconsistently or its contents to appear to change.
* <li>They disallow {@code null} keys and values. Attempts to create them with
- csr of
-
JDK-8328821 Map.of() derived view collection mutators should throw UnsupportedOperationException
-
- Open
-