Integer 和Int的区别+new Integer和int值比较的问题

Integer 和Int的区别

Integer是包装类,|  需要实例化才能用,|  默认值是null,|  存的是对象的引用。

Int是基础数据类型,|  直接可以用,     |   默认值是0,     |  直接存数据。

 

Integer 和int 的==比较

//数值范围在-128到127之间时。
        int d = 100;
        Integer a = 100;
        Integer b = 100;
        Integer c = new Integer(100);
        System.out.println(a == b);  //true
        System.out.println(a == c);  // false
        System.out.println(a == d);  //true

        //范围不在-128到127之间的int
        int aa = 200;
        int bb = 200;
        Integer cc = new Integer(200);
        System.out.println(aa == bb);  //true 
        System.out.println(aa == cc); //false

        //范围不在-128到127之间的Integer
        Integer aaa = 200;
        Integer bbb = 200;
        System.out.println(aaa == bbb);  //false 
        System.out.println(aa == aaa);  //true integer和int比,会自动拆箱,比较值的大小

int和int可以直接比较(==),虽然==比的是地址,但那是针对包装类型(也就是new出来的类型而言的),而int是基础类型,所以比较的是值的大小,没有-128至127的限制。

Integer 和int的值相互比较的时候(==),比较的是值的大小,因为integer会自动拆箱,

Integer i=127Integer j=127相互比较的时候(==),是相等的;

Integer i=128Integer j=128相互比较的时候(==),是不等的;

因为JVM会自动维护八种基本类型的常量池,int常量池中初始化-128~127的范围,所以当为Integer i=127时,

在自动装箱过程中是取自常量池中的数值,而当Integer i=128时,128不在常量池范围内,

所以在自动装箱过程中需new 128,所以地址不一样。

 

equals 和==的比较比较麻烦

Integer重写了equals,比较的是值,类似的string也是比较的值。

而== 比较的是地址。

public class IntegerTest {
    public static void main(String[] args) {


        Integer a = 1;
        Integer d = 1;
        int b = 1;
        Integer c = new Integer(1);
        System.out.println(a == b);  //True,自动拆箱装箱,比的是值
        System.out.println(a == c); // false ==比的是地址,不是一个对象。
        System.out.println(a == d); // True a 和d是一个对象?
        System.out.println(b == c); //True Integer自动拆箱,比的值
        System.out.println(a.equals(c)); //True
        System.out.println(a.equals(b)); //True Integer重写了equals,比较的是值
        System.out.println(b.equals(c));  //这句是错误的,因为int类型的b没有equals方法。
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章