[JAVA] ConcurrentHashMap erlaubt keine Null für Schlüssel und Wert

Beachten Sie, dass ConcurrentHashmap eine thread-sichere Version von HashMap ist, es gibt jedoch einige Unterschiede.

Basic: Map Irgendwie der Unterschied in der Karte

HashMap

Erlaube null. Nicht threadsicher.

ConcurrentHashMap

[Hinzugefügt von Java 1.5], um eine exklusive Kontrolle zu erreichen (https://qiita.com/YanHengGo/items/21ca9408fb59ddb7a566). Es ist jedoch nicht null zulässig.

ConcurrentHashMap.java


    /**
     * Maps the specified key to the specified value in this table.
     * Neither the key nor the value can be null.
     *
     * <p> The value can be retrieved by calling the <tt>get</tt> method
     * with a key that is equal to the original key.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>
     * @throws NullPointerException if the specified key or value is null
     */
    public V put(K key, V value) {
        if (value == null)
            throw new NullPointerException();
        int hash = hash(key.hashCode());
        return segmentFor(hash).put(key, hash, value, false);
    }

Beispiel:

Sample1.java


        ConcurrentHashMap map = new ConcurrentHashMap();
        map.put("test", null);
Exception in thread "main" java.lang.NullPointerException
	at java.util.concurrent.ConcurrentHashMap.put(ConcurrentHashMap.java:881)
	at playground.Sample1.main(Sample1.java:9)

Sample2.java



        ConcurrentHashMap map = new ConcurrentHashMap();
        map.put(null, "test");
Exception in thread "main" java.lang.NullPointerException
	at java.util.concurrent.ConcurrentHashMap.put(ConcurrentHashMap.java:882)
	at playground.Sample2.main(Sample2.java:12)

Ergebnis

Es gibt eine Quelle, die dies beim Ersetzen von HashMap → ConcurrentHashmap tut.

Realcode.java


        if (inputvalue == null) {
            return;
        }

Recommended Posts

ConcurrentHashMap erlaubt keine Null für Schlüssel und Wert
In Bezug auf die Zuordnung von Hash-Schlüssel und Wert
Funktioniert die Escape-Sequenz (\) nicht? (für Mac)
Der öffentliche Schlüssel für jenkins-2.249.1-1.1.noarch.rpm ist nicht installiert
Richtlinien für die Schreibverarbeitung, wenn Werte in Java vorhanden sind / nicht vorhanden Optional