map.put 返回什么? [英] What does map.put return?
问题描述
我尝试获取map接口的put方法的返回类型.当我第一次打印时,它正在打印 null 并且在更新密钥后我得到了以前的值.那么,谁能告诉我map接口中put方法的返回类型是什么?
I tried to get the return type of put method of the map interface. When I print for the first time it is printing null and after updating the key I get the previous value. So, can anyone tell me what is the return type of the put method in the map interface?
Map<Integer, String> map = new HashMap<Integer, String>();
System.out.println(map.put(1, "ABC"));
System.out.println(map.put(1, "XYZ"));
Output:
null
ABC
推荐答案
map中put方法的返回类型是值类型.
return type of put method in the map is the value type.
put 的方法声明:V put(K key, V value);
Method declaration of put: V put(K key, V value);
哪里,
key:与指定值关联的键
key: key with which the specified value is to be associated
value:与指定键关联的值
value: value to be associated with the specified key
返回类型:与键关联的前一个值,如果键没有映射,则为null.如果实现支持 null 值,则返回 null 还可以指示映射先前将 null 与键关联.
return type: The previous value associated with the 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.
例如 -
System.out.println(map.put(1, "ABC"));-->在这种情况下,没有与键 1 关联的值,因此它返回 null
System.out.println(map.put(1, "ABC")); --> In this case there is no value associated with the key 1, so it returns null
System.out.println(map.put(1, "XYZ"));-->当您针对已存储的键存储新值时,新值将替换先前的值,而 put 方法将返回先前被覆盖的值.在这种情况下,它将返回ABC.
System.out.println(map.put(1, "XYZ")); --> When you are storing a new value against an already stored key, the new value will replace the previous value and the put method will return the previous value which was overridden. In this case, it will return ABC.
这篇关于map.put 返回什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!