Java 9 introduced new factory methods for the List , Set and Map interfaces. These methods allow you to quickly instantiate a Map object with values on a single line. Now, considering:
Map<Integer, String> map1 = new HashMap<Integer, String>(Map.of(1, "value1", 2, "value2", 3, "value3")); map1.put(4, null);
The above is permitted without any exceptions if we do:
Map<Integer, String> map2 = Map.of(1, "value1", 2, "value2", 3, "value3", 4, null );
He throws out:
Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Objects.requireNonNull(Objects.java:221) ..
I cannot get, why null is not allowed in the second case.
I know that HashMap can take null as a key, as well as a value, but why was this limited in the case of Map.of?
The same thing happens with java.util.Set.of("v1", "v2", null) and java.util.List.of("v1", "v2", null) .
java java-9
hi.nitish Jul 20 '17 at 9:16 2017-07-20 09:16
source share