Java参考变量使用一单元增量(减少)操作使用时无法正常工作

发布于 2025-01-22 17:58:08 字数 790 浏览 2 评论 0原文

在代码中,我将输出视为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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谈场末日恋爱 2025-01-29 17:58:08

-操作是变量的操作。对于Integer变量,它将变量更新为新的参考值...表示数字-1。它等同于

// cnt--;
cnt = Integer.valueOf(cnt.intValue() - 1);

-操作员无法更改在现有整数中保存的值对象。 整数对象是不可变的!

因此,当您增加变量时,它不会影响hashmap条目中的值。

The -- operation is an operation on a variable. In the case of an Integer variable, it updates the variable to a new reference value ... representing the number - 1. It is equivalent to

// cnt--;
cnt = Integer.valueOf(cnt.intValue() - 1);

The -- operator cannot change the value held within the existing Integer object. Integer objects are immutable!

So ... when you increment the variable, it doesn't affect the value in the HashMap entry.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文