java - map.put 返回什么?

标签 java dictionary hashmap return-type

我试图获取 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/

相关文章:

arrays - 以键为数组类型的散列

java - Android 如何使用 Caldroid Lib 中异步任务的数据填充日历

java - 构造函数中的同步以使其先于发生

java - 从 map 中获取最高 n 个数字的最简洁方法?

java - 无法实现 BufferUntil RxJava

c++ - 初始化 1000 个 map 元素

java - 使用什么代替 ArrayList 对数据进行分组?

java - 从 Java HashMap 获取 Integer 值时是否需要调用 intValue() 方法?

java - 为什么将单例对象设为私有(private)而不是公开

Java 库哪些不是二进制文件?