原文链接:Map用法总结
Constructs an empty HashMap with the default initial capacity (16) (mutable
)
// Constructs an empty HashMap with the default initial capacity (16) and the default load fact
// Since:1.2
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
System.out.println(map); // {key1=value1}
com.google.common.collect.Maps(mutable
)
// com.google.common.collect
// Creates a mutable, empty HashMap instance.
Map<String, String> map = Maps.newHashMap();
map.put("key1", "value1");
System.out.println(map); // {key1=value1}
java.util.Collections(immutable
)
// Returns an empty map (immutable). This map is serializable.
// Since: 1.5
Map<String, String> map = Collections.emptyMap();
map.put("key1", "value1");
Exception in thread "main" java.lang.UnsupportedOperationException
at java.base/java.util.AbstractMap.put(AbstractMap.java:209)
java.util.Collections(immutable
)
// The empty map (immutable). This map is serializable.
// Since:1.3
Map map = Collections.EMPTY_MAP;
map.put("key1", "value1");
Exception in thread "main" java.lang.UnsupportedOperationException
at java.base/java.util.AbstractMap.put(AbstractMap.java:209)
org.apache.commons.collections.MapUtils(immutable
)
// An empty unmodifiable map.
// This was not provided in JDK1.2.
Map map = MapUtils.EMPTY_MAP;
map.put("key1", "value1");
Exception in thread "main" java.lang.UnsupportedOperationException
at org.apache.commons.collections.map.UnmodifiableMap.put(UnmodifiableMap.java:108)