两个Integer比较

两个Integer类型比较不能使用==,要使用equals,   == 在-127~128是可以用的,超出这个范围就不行
public static void main(String[] args) throws Exception {
        Integer a = -129;
        Integer b = -129;
        if(a==b){
            System.out.print("相等");
        }else{
            System.out.print("bu 相等");//输出这个
        }
    }

原因如下:

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 一个出来,这时比较的是内存地址,不是同一对象.

 

原文地址:https://www.cnblogs.com/cui0614/p/10690794.html