我预计以下代码片段是等效的:
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。
为什么?既然Integer
是HashMap
中的引用,为什么增量没有反映,我需要做一个put
?
count
是一个局部变量。它指向不可变类的实例,Integer
。
当您将其递增为:
++count;
这只是语法糖:
count = Integer.valueOf(count.intValue() + 1);
您正在重新分配count
.就这样。