Integer面试问题

来源:互联网 发布:qq加好友软件 编辑:程序博客网 时间:2024/05/21 06:33

昨天面试的时候被问到

Integer a=128;

Integer b=128;

问 a==b 跟a.equal(b)的结果;

这里就要分Integer值位-128-127的情况

在-128到127的情况下, a==b的值为true;   a.equals(b)的值为true;

这里就要分Integer值位小于-128和大于127的情况

在-128到127的情况下, a==b的值为false;   a.equals(b)的值为true;


public static Integer valueOf(int i) {  
      assert IntegerCache.high >= 127;  
      if (i >= IntegerCache.low && i <= IntegerCache.high)  
          return IntegerCache.cache[i + (-IntegerCache.low)];  
      return new Integer(i);  
  } 

在值小于-128和值大于127的情况 会调用 Integer i=new Integer(xxx);

从而导致地址的不同,因此a==b返回值为false;


原创粉丝点击