==具有抽象数据类型,同一种条件的结果不同

时间:2012-08-14 15:40:31

标签: java memory memory-management jvm shared-memory

  

可能重复:
  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

您也可以使用negetive值。当您使用值观察输出时,它们的行为会有所不同。造成这种不同结果的原因是什么?

对于任何数字,范围应为-127到+127,然后==为真或为假。

(全部) 伙计们抱歉这是一个拼写错误,我把它作为原始错误,但它是抽象的。抱歉这个错误。现在纠正了......

4 个答案:

答案 0 :(得分:9)

整数不是原始的,它是一个对象。如果您使用intlong,则只会获得true

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

这是在Java Language Specification #5.1.7

中定义的

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

  

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

答案 1 :(得分:1)

Integer不是基本类型,而是包装类型。请参阅:http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

答案 2 :(得分:0)

Integer是对象(包装类),而不是基本类型

最好进行比较,例如a1.intValue() == a2. intValue()代替(或)equals()

答案 3 :(得分:0)

首先整数不是原语(int是)。但要回答为什么会发生这种情况,这是因为在Integer实现中找到了内部缓存:

 /**
 * Cache to support the object identity semantics of autoboxing for values between 
 * -128 and 127 (inclusive) as required by JLS.
 *
 * The cache is initialized on first usage. During VM initialization the
 * getAndRemoveCacheProperties method may be used to get and remove any system
 * properites that configure the cache size. At this time, the size of the
 * cache may be controlled by the vm option -XX:AutoBoxCacheMax=<size>.
 */

所以从本质上说,比较两个已经缓存的整数,你将同一个对象与自身进行比较,所以==返回true,但是当你比较127以上或-127以下的整数(非缓存整数)时你正在比较两个不同的整数实例。

如果您使用equals或compareTo方法,您将获得期望看到的内容。

相关问题