RFR(s): JDK-8144952: add wildcards to the Map.ofEntries() method

Stuart Marks stuart.marks at oracle.com
Thu Dec 10 00:22:34 UTC 2015


Hi all,


Joe Darcy pointed out that API changes I pushed into jdk9-dev yesterday are 
missing wildcards from the Map.ofEntries() method. Please see this bug:

   https://bugs.openjdk.java.net/browse/JDK-8144952

The Map.ofEntries() method currently has the following declaration:

   static <K, V> Map<K, V> ofEntries(Entry<K, V>... entries)

it should be changed to

   static <K, V> Map<K, V> ofEntries(Entry<? extends K, ? extends V>... entries)

This doesn't make all that much difference in practice. For example, this works:

   Map<Number, Number> map1 = MapOfEntries(entry(1, 2.0), entry(3.0f, 4L));

However, this does not:

   Map.Entry<Integer,Double> e1 = Map.entry(1, 2.0);
   Map.Entry<Float,Long> e2 = Map.entry(3.0f, 4L);
   Map<Number,Number> map = Map.ofEntries(e1, e2);

After adding the wildcards, the latter example compiles fine. This is a pretty 
unusual case, but for maximum flexibility it's probably a good idea to add the 
wildcards anyway.

Please review the diff appended below.

Thanks,

s'marks

# HG changeset patch
# User smarks
# Date 1449706837 28800
#      Wed Dec 09 16:20:37 2015 -0800
# Node ID b6540a8b7ab064600fe49a8bc678ad96127090ca
# Parent  7f644a5d554a67457f3dd535c4435643d3f65569
8144952: add wildcards to the Map.ofEntries() method
Reviewed-by: XXX

diff -r 7f644a5d554a -r b6540a8b7ab0 src/java.base/share/classes/java/util/Map.java
--- a/src/java.base/share/classes/java/util/Map.java	Wed Dec 09 15:27:21 2015 -0500
+++ b/src/java.base/share/classes/java/util/Map.java	Wed Dec 09 16:20:37 2015 -0800
@@ -1670,9 +1670,9 @@
       */
      @SafeVarargs
      @SuppressWarnings("varargs")
-    static <K, V> Map<K, V> ofEntries(Entry<K, V>... entries) {
+    static <K, V> Map<K, V> ofEntries(Entry<? extends K, ? extends V>... entries) {
          Map<K, V> map = new HashMap<>(entries.length * 4 / 3 + 1); // throws 
NPE if entries is null
-        for (Entry<K, V> e : entries) {
+        for (Entry<? extends K, ? extends V> e : entries) {
              // next line throws NPE if e is null
              map.put(Objects.requireNonNull(e.getKey()), 
Objects.requireNonNull(e.getValue()));
          }
diff -r 7f644a5d554a -r b6540a8b7ab0 test/java/util/Map/MapFactories.java
--- a/test/java/util/Map/MapFactories.java	Wed Dec 09 15:27:21 2015 -0500
+++ b/test/java/util/Map/MapFactories.java	Wed Dec 09 16:20:37 2015 -0800
@@ -377,4 +377,13 @@
          assertEquals(sie.toString(), kvh1.toString());
      }

+    // compile-time test of wildcards
+    @Test
+    public void entryWildcardTests() {
+        Map.Entry<Integer,Double> e1 = Map.entry(1, 2.0);
+        Map.Entry<Float,Long> e2 = Map.entry(3.0f, 4L);
+        Map<Number,Number> map = Map.ofEntries(e1, e2);
+        assertEquals(map.size(), 2);
+    }
+
  }



More information about the core-libs-dev mailing list