if (int == Integer) NullPointException

//person.age为Integer类型
if(2 == person.age) {
    
    
	//如果person.age == null的话,会报空指针 
	//	因为它会将 person.age拆箱成基本数据类型int,然后调用intValue()方法,自然就会报空指针了
}

// 拆箱时调用的方法
 public int intValue() {
    
    
        return value;
    }

// 装箱时调用的方法
 public static Integer valueOf(int i) {
    
    
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
/**
:返回表示指定{@code INT}值的{@code整数}实例。 如果不需要新的{@code整数}例如,这种方法一般应优先使
用构造{@link#整数(INT)},因为此方法可能通过缓存经常产生显著更好的空间和时间性能 请求的值。
 **这种方法将在范围内始终缓存值-128到127,包容性,并可以外接高速缓存的这个范围以外的值**。 @Param
 我的{@code INT}值。
 返回:表示{@code I} {一个整数@code}实例。 @since 1.5
*/
//对于-128到127之间的数,会进行缓存,Integer i6 = 127时,会将127进行缓存,下次再写Integer i7 = 127
//时,就会直接从缓存中取,就不会new了。
 public static Integer valueOf(int i) {
    
    
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

Ingeter是int的包装类,int的初值为0,Ingeter的初值为null。
无论如何,Integer与new Integer()不会相等。不会经历拆箱过程,i8的引用指向堆,而i4指向专门存放他的内存(常量池),他们的内存地址不一样,使用 == 比较都为false。
两个都是非new出来的Integer,使用 == 比较,如果数在-128到127之间,则是true,否则为false
两个都是new出来的,==比较都为false。若要比较值是否相等,需使用equals方法进行比较。
int和Integer(无论new否)比,都为true,因为会把Integer自动拆箱为int再去比。


        Integer a1 = 127;
        Integer a2 = 127;
        System.out.println(a1 == a2);// true
        System.out.println(a1.equals(a2));// true
        System.out.println("==========================");

        Integer b1 = 128;
        Integer b2 = 128;
        System.out.println(b1 == b2);// false
        System.out.println(b1.equals(b2));// true
        System.out.println("==========================");

        Integer c1 = 128;
        int c2 = 128;
        System.out.println(c1 == c2);// true
        System.out.println(c1.equals(c2));// true
        System.out.println("==========================");

        int d1 = 127;
        Integer d2 = null;
        System.out.println(d1 == d2);// NullPointerException
        System.out.println("==========================");

        int e1 = 128;
        Integer e2 = 128;
        Integer e3 = new Integer(128);
        System.out.println(e1 == e2); true
        System.out.println(e2 == e3); //false
        System.out.println(new Integer(e1).equals(e2)); //true

        System.out.println("==========================");
        Integer f1 = 127;
        Integer f2 = new Integer(127);
        System.out.println(f1 == f2); //false
        System.out.println(f1.equals(f2)); //true

Guess you like

Origin blog.csdn.net/loveyour_1314/article/details/105710401