我试图获取 map 接口(interface)的put方法的返回类型。当我第一次打印时,它打印 null,更新 key 后我得到以前的值。 那么,谁能告诉我map接口(interface)中put方法的返回类型是什么?
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
最佳答案
根据 java 文档:
The put 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 the key if the implementation supports null values.)
在您的情况下,当您执行 map.put(1, "ABC")
时,没有任何内容与 key 1
关联,因此它返回 null
但是当您使用 put(1, "XYZ")
时,针对 key 1
已经存在一个条目
,因此它返回“ABC”
关于java - map.put 返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60275379/