Java参考变量使用一单元增量(减少)操作使用时无法正常工作
在代码中,我将输出视为true,0
。但是,输出为true,1
。由于CNT是使用键3的键值对值的引用变量。我认为操作cnt-
;将更改参考变量指向的值。但是,显示的Bellow的实验代码似乎并没有改变哈希图中的值。 我很困惑,因为如果get
方法返回实例的副本,则equals
操作应返回false。然而,它返回true,因此它只是返回对实例的引用。那为什么一单一的减少操作不起作用呢?
先感谢您。欢迎对问题清晰的任何反馈。
import java.util.HashMap;
import java.util.Map;
public class Equals {
public static void main(String[] args) {
int[] nums1 = new int[] { 1, 2, 3, 4, 5 };
Map<Integer, Integer> map = new HashMap<>();
for (int n : nums1) {
map.put(n, map.getOrDefault(n, 0) + 1);
}
Integer cnt = map.getOrDefault(3, 0);
Integer cnt2 = map.get(3);
System.out.println(cnt.equals(cnt2));
cnt--;
System.out.println(cnt2);
}
}
In the code bellow I excpected the Output to be true, 0
. However the output is true, 1
. Since cnt is a reference variable to the Value of the Key-Value Pair with Key 3. I thought the operation cnt--
; would change the value where the reference variable is pointing at. However the experimental code shown bellow doesn't seem to change the value in the HashMap.
I'm confused because if get
method returns a copy of the instance, then the equals
operation should return false. Yet it is returning true so it is just returning a reference to an instance. Then why is that unary decrement operation not working?
Thank you in advance. Any feedback to the clarity of the question is welcome.
import java.util.HashMap;
import java.util.Map;
public class Equals {
public static void main(String[] args) {
int[] nums1 = new int[] { 1, 2, 3, 4, 5 };
Map<Integer, Integer> map = new HashMap<>();
for (int n : nums1) {
map.put(n, map.getOrDefault(n, 0) + 1);
}
Integer cnt = map.getOrDefault(3, 0);
Integer cnt2 = map.get(3);
System.out.println(cnt.equals(cnt2));
cnt--;
System.out.println(cnt2);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
-
操作是变量的操作。对于Integer
变量,它将变量更新为新的参考值...表示数字-1。它等同于-
操作员无法更改在现有整数中保存的值
对象。整数
对象是不可变的!因此,当您增加变量时,它不会影响
hashmap
条目中的值。The
--
operation is an operation on a variable. In the case of anInteger
variable, it updates the variable to a new reference value ... representing the number - 1. It is equivalent toThe
--
operator cannot change the value held within the existingInteger
object.Integer
objects are immutable!So ... when you increment the variable, it doesn't affect the value in the
HashMap
entry.