简体   繁体   中英

Why does System.out.println(map.put(1,“test”)) print null value?

class Test3 {  
    public static void main(String args[]){  
        Map<Integer, String> aa = new HashMap();
        System.out.println(aa.put(1, "test"));
    }  

}

whenever I execute this statement it prints null value. I want to know why it printing the null value. What is happening?

From the Javadoc of Map.put :

 V put(K key, V value)

...

Returns : the previous value associated with key, or null if there was no mapping for key.

The map is empty before the call to put , so "there was no mapping for key", so null is returned.

implementation of put is something like below

@Override
    public V put(K key, V value) {
        return putImpl(key, value);
    }

If the map previously contained a mapping for the key, the old value is replaced. else null will return because there is no mapping.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM