整数不是引用吗?为什么公司不更新哈希图值?



我预计以下代码片段是等效的:

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中的引用,为什么增量没有反映,我需要做一个put

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

当您将其递增为:

++count;

这只是语法糖:

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

您正在重新分配count.就这样。

最新更新