/**
* Returns the empty map (immutable). This map is serializable.
*
* <p>This example illustrates the type-safe way to obtain an empty set:
* <pre>
* Map<String, Date> s = Collections.emptyMap();
* </pre>
* Implementation note: Implementations of this method need not
* create a separate <tt>Map</tt> object for each call. Using this
* method is likely to have comparable cost to using the like-named
* field. (Unlike this method, the field does not provide type safety.)
*
* @see #EMPTY_MAP
* @since 1.5
*/
@SuppressWarnings("unchecked")
public static final <K,V> Map<K,V> emptyMap() {
return (Map<K,V>) EMPTY_MAP;
}
Die obige Funktion gibt eine unveränderbare leere Map zurück.Warum haben wir eine unveränderliche leere Karte?
public static final Map EMPTY_MAP = new EmptyMap<>();
EmptyMap Klasse ist als
/**
* @serial include
*/
private static class EmptyMap<K,V>
extends AbstractMap<K,V>
implements Serializable
{
private static final long serialVersionUID = 6428348081105594320L;
public int size() {return 0;}
public boolean isEmpty() {return true;}
public boolean containsKey(Object key) {return false;}
public boolean containsValue(Object value) {return false;}
public V get(Object key) {return null;}
public Set<K> keySet() {return emptySet();}
public Collection<V> values() {return emptySet();}
public Set<Map.Entry<K,V>> entrySet() {return emptySet();}
public boolean equals(Object o) {
return (o instanceof Map) && ((Map<?,?>)o).isEmpty();
}
public int hashCode() {return 0;}
// Preserves singleton property
private Object readResolve() {
return EMPTY_MAP;
}
}
folgt Was ist die Verwendung solcher Klasse und Dienstprogramm-Methode? Ich habe versucht,
Map myMap = Collections.emptyMap();
myMap.put("Name","John");
und ich Exception in thread "main" java.lang.UnsupportedOperationException
weil Sammlung unveränderlich ist keine Modifikation unterstützen. Also, was ist die Verwendung einer solchen Datenstruktur?
Ich bin mir nicht sicher..aber meine Vermutung ist, dass dies in etwas wie ein Null-Objekt-Muster hilfreich ist. Anstatt eine Nullreferenz von einer Methode zurückzugeben, können Sie eine leere Map zurückgeben. – Asha
mögliches Duplikat von [Collections.emptyMap() vs. new HashMap()] (http://stackoverflow.com/questions/14846920/collections-emptymap-vs-new-hashmap) – assylias