简体   繁体   中英

Printing map value by assigning into string variable

HashMap<Integer, String> map = new HashMap<Integer, String>();
String prevObject=map.put(1, "JavaGoal");
System.out.println(prevObject);

The solution is null here. But I don't know why it comes as null.

From the javadoc for the return value of put

the previous value associated with key, or null if there was no mapping for key.(A null return can also indicate that the mappreviously associated null with key.)

ie there is no pre-existing value for that key. Typically get is used to retrieve the current value

 System.out.println(map.get(1));
HashMap<Integer, String> map = new HashMap<Integer, String>();
String prevObject=map.put(1, "JavaGoal");
System.out.println(prevObject);

The solution is null here. But I don't know why it comes as null.

HashMap<Integer, String> map = new HashMap<Integer, String>();

The above line of code creates an instance of class HashMap that contains no entries. In other words, the HashMap is empty.

String prevObject = map.put(1, "JavaGoal");

The above line of code adds a single entry to the HashMap . The HashMap now contains exactly one entry. The entry contains a key and a value. The key is the integer 1 and the value is the string JavaGoal .

Method put also returns the previous value of the entry whose key was the integer 1 . But before calling method put there was no entry in the HashMap with that key. In fact there were no entries. Hence there was no previous value. Hence the method put returned null.

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