两个integer数据判断相等用==还是equals

两个Integer类型比较不能使用==,要使用equals, == 在-127~128是可以用的,超出这个范围就不行

public static void main(String[] args) throws Exception {

Integer a = 10;
Integer b = 10;
System.out.print(a==b);//true

Integer a = -129;
Integer b = -129;      System.out.print(a==b);//false
}

原因如下:

static final Integer cache[] = new Integer[-(-128) + 127 + 1];
  static {
   for(int i = 0; i < cache.length; i++)
    cache[i] = new Integer(i - 128);
  }

源码中cache已有-128到127,不在这范围的会新new 一个出来,这时比较的是内存地址,不是同一对象

推荐 收藏
评论(0) 阅读(360)
刷新评论 返回顶部
Lottie最新博客