java的行为不一致==

Inconsistent behavior on java#39;s ==(java的行为不一致==)

本文介绍了java的行为不一致==的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这段代码:

class test {
   public static void main(String[] args) {
      test inst_test = new test();
      int i1 = 2000;
      int i2 = 2000;
      int i3 = 2;
      int i4 = 2;
      Integer Ithree = new Integer(2); // 1
      Integer Ifour = new Integer(2); // 2
      System.out.println( Ithree == Ifour );
      inst_test.method( i3 , i4 );
      inst_test.method( i1 , i2 );
   }
   public void method( Integer i , Integer eye ) {
      System.out.println(i == eye );
   }
}

打印出来:

false
true
false

我理解第一个 false,== 运算符只检查两个引用是否在同一个对象上工作,在这种情况下不是.

I understand the first false, the == operator only checks if two references are working on the same object, which in this case aren't.

下面的 truefalse 让我摸不着头脑.为什么 Java 会认为 i3i4 相等但 i1i2 不同?两者都被包装成整数,不应该 both 评估为假吗?这种不一致是否有实际原因?

The following true and false have me scratching my head. Why would Java consider i3 and i4 equal but i1 and i2 different? Both have been wrapped to Integer, shouldn't both evaluate to false? Is there a practical reason for this inconsistency?

推荐答案

将基元自动装箱到对象中(在您对 method 的调用中使用的方法是使用小值缓存.来自 Java 语言规范第 5.1.7 节:

Autoboxing of primitives into objects (as used in your calls to method uses a cache of small values. From the Java Language Specification section 5.1.7:

如果被装箱的值p为真,false,一个字节,一个字符在范围内u0000 到 u007f,或者一个 int 或 short介于 -128 和 127 之间的数字,然后让r1 和 r2 是任意两个的结果p的拳击转换.它总是r1 == r2 的情况.

If the value p being boxed is true, false, a byte, a char in the range u0000 to u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

紧随其后的规范讨论部分也很有趣.值得注意的是,如果 JVM 愿意,它可以缓存 更多 值 - 你不能确定这样做的结果:

The discussion part of the spec immediately following that is interesting too. Notably a JVM can cache more values if it wants to - you can't be sure of the results of doing:

Integer i1 = 129;
Integer i2 = 129;
boolean b = (i1 == i2);

这篇关于java的行为不一致==的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:java的行为不一致==

基础教程推荐