java上的行为不一致== [英] Inconsistent behavior on java's ==

查看:203
本文介绍了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.

以下 true false 让我挠头。为什么Java会考虑 i3 i4 等于但 i1 i2 与众不同?两者都被包装到Integer,不应该两者评估为false?是否存在这种不一致的实际原因?

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?

推荐答案

将基元自动装箱到对象中(用于调用<$ c $) c>方法使用小值的缓存。来自 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:


如果列表的值为真,则
false,一个字节,
\ u0000到\ u007f范围内的字符,或-128到127之间的int或short
数字,然后让
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上的行为不一致==的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆