==对于Abstract数据类型,相同条件下的不同结果 [英] == with Abstract datatypes, different results for the same kind of conditions

查看:107
本文介绍了==对于Abstract数据类型,相同条件下的不同结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
整数包装对象仅共享相同的实例值127内?

Possible Duplicate:
Integer wrapper objects share the same instances only within the value 127?

public class test
{
  public static void main(String args[])
  {
    Integer a1=127;
    Integer a2=127;
    System.out.println(a1==a2); //output: true

    Integer b1=128;
    Integer b2=128;
    System.out.println(b1==b2); //output: false

    Long c1=127L;
    Long c2=127L;
    System.out.println(c1==c2); //  output: true

    Long d1=128L;
    Long d2=128L;
    System.out.println(d1==d2); //output: false 
  }
}

输出:

true
false
true
false

您也可以使用取值.当您观察带有值的输出时,它们的行为会有所不同.如此不同的结果可能是什么原因?

You can use negetive values too. When you observe the outputs with the values, they behave differently. What can be the reason for such different results?

对于任何数字,范围应为-127到+127,则==为true或false.

For any number the range should be -127 to +127, then == is true or it is false.

(全部) 抱歉,这是一个错字错误,我误认为它是原始错误,但它是抽象的.对不起,我的错.现在已更正...

(All) Guys sorry it was a typo error, by mistake i put it as primitive, but it's abstract. sorry for the mistake. Now corrected...

推荐答案

整数不是基元,而是对象.如果使用intlong,则只会得到true.

Integer is not a primitive, it is an object. If you used int or long you would only get true.

之所以会得到此结果,是因为Integer缓存了-128到127之间的值,因此Integer i = 127将始终返回相同的引用. Integer j = 128不一定会这样做.然后,您将需要使用equals来测试基础int的相等性.

The reason why you get this result is that Integers are cached for values between -128 and 127 so Integer i = 127 will always return the same reference. Integer j = 128 will not necessarily do so. You will then need to use equals to test for equality of the underlying int.

这在 Java语言规范#5.1.7 .

请注意,超出该范围的值的行为[-128; 127]未定义:

Note that the behaviour for values outside that range [-128; 127] is undefined:

例如,较少内存限制的实现可能会缓存所有char和short值,以及-32K到+ 32K范围内的int和long值.

Less memory-limited implementations might, for example, cache all char and short values, as well as int and long values in the range of -32K to +32K.

这篇关于==对于Abstract数据类型,相同条件下的不同结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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