8144952: add wildcards to the Map.ofEntries() method

Reviewed-by: darcy, psandoz, chegar
This commit is contained in:
Stuart Marks 2015-12-11 17:01:01 -08:00
parent 7e3889ef43
commit 82c454ff4a
2 changed files with 11 additions and 2 deletions

View File

@ -1670,9 +1670,9 @@ public interface Map<K, V> {
*/
@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()));
}

View File

@ -377,4 +377,13 @@ public class MapFactories {
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);
}
}