为什么 Java 看不到整数相等?

编程入门 行业动态 更新时间:2024-10-26 12:25:31
本文介绍了为什么 Java 看不到整数相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有应该相等的整数(我通过输出验证它).但是在我的 if 条件下,Java 没有看到这些变量具有相同的值.

I have integers that are supposed to be equal (and I verify it by output). But in my if condition Java does not see these variables to have the same value.

我有以下代码:

if (pay[0]==point[0] && pay[1]==point[1]) { game.log.fine(">>>>>> the same"); } else { game.log.fine(">>>>>> different"); } game.log.fine("Compare:" + pay[0] + "," + pay[1] + " -> " + point[0] + "," + point[1]);

它产生以下输出:

FINE: >>>>>> different FINE: Compare:: 60,145 -> 60,145

可能我必须补充一点,point 是这样定义的:

Probably I have to add that point is defined like that:

Integer[] point = new Integer[2];

和 pay 我们从循环构造函数中取出:

and pay us taken from the loop-constructor:

for (Integer[] pay : payoffs2exchanges.keySet())

所以,这两个变量都是整数类型.

So, these two variables both have the integer type.

推荐答案

查看这篇文章:盒装值和平等

当使用 == 或 ==s、Longs 或 Booleans 比较包装器类型时code>!=,您将将它们作为参考进行比较,而不是作为值进行比较.

When comparing wrapper types such as Integers, Longs or Booleans using == or !=, you're comparing them as references, not as values.

如果两个变量指向不同的对象,它们不会==彼此,即使对象代表相同的值.

If two variables point at different objects, they will not == each other, even if the objects represent the same value.

示例: 使用 == 和 != 比较不同的 Integer 对象.

Example: Comparing different Integer objects using == and !=. Integer i = new Integer(10); Integer j = new Integer(10); System.out.println(i == j); // false System.out.println(i != j); // true

解决方案是使用 .equals()...

The solution is to compare the values using .equals()…

示例: 使用 .equals(…)

Integer i = new Integer(10); Integer j = new Integer(10); System.out.println(i.equals(j)); // true

...或显式拆箱操作数.

…or to unbox the operands explicitly.

示例:强制取消装箱:

Integer i = new Integer(10); Integer j = new Integer(10); System.out.println((int) i == (int) j); // true

参考资料/进一步阅读

  • Java:装箱值和相等性
  • Java:基元 vs 对象和引用
  • Java:包装类型
  • Java:自动装箱和拆箱

更多推荐

为什么 Java 看不到整数相等?

本文发布于:2023-10-16 05:19:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1496614.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!