gpt4 book ai didi

java - Integer 不是一个引用吗?为什么 inc 不更新 hashmap 值?

转载 作者:行者123 更新时间:2023-12-01 19:54:05 27 4
gpt4 key购买 nike

我期望以下代码片段是等效的:

Integer count = occurences.get(c);  
if(count == null) {
count = 0;
occurences.put(c, count);
}
++count;

Integer count = occurences.get(c);  
if(count == null) {
count = 0;
occurences.put(c, count);
}
occurences.put(c, count + 1);

但是当我运行程序时,第一个代码段的 count 始终为 0。
这是为什么?由于 IntegerHashMap 中的引用,为什么增量没有反射(reflect)出来,而我需要执行 put

最佳答案

count 是一个局部变量。它指向一个不可变类的实例,Integer

当你增加它时:

++count;

这只是语法糖:

count = Integer.valueOf(count.intValue() + 1);

您正在重新分配计数。仅此而已。

关于java - Integer 不是一个引用吗?为什么 inc 不更新 hashmap 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50221368/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com