Map liefert bei put null als Ergebnis

ProChris

Mitglied
Hallo,

weiss jemand warum s hier null ist? Ich hätte jetzt erwartet, dass put als Ergebnis das liefert, was als value rein kommt.

Java:
		Map<String, String> d = new HashMap<String, String>();
		
		String s = d.put("q", "ww");
		System.out.println(s);

Viele Grüße

ProChris
 
Ich hätte jetzt erwartet, dass put als Ergebnis das liefert, was als value rein kommt.
Wie kommst du auf diese Idee?

Map (Java Platform SE 7 )
Returns the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key, if the implementation supports null values.)

EDIT: Steht auch schon so in der über zehn Jahre alten Java 2 Doc: Map (Java 2 Platform SE v1.4.2)
 
Zuletzt bearbeitet:
Lies einfach mal dieses Beispiel dann verstehst du (Vorallem den Zeilenkommentar 😉)


Java:
public static void main(String... args) {
        
        Map<String,String> smap = new HashMap();
        
        System.out.println(smap.put("Test","test"));
        System.out.println(smap.put("Test","bla :O"));
        
        //Überraschung. Es gibt die null aus weil es noch keinen Wert in der Map gibt den es ausgeben kann ;) Erst beim zweiten mal !!!!
        
    }


lg

Rene
 

Zurück
Oben