Integer和int的比较大小

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011136197/article/details/82111175

1.Int和Integer比较大小

public static void main(String[] args) {

        int i = 10;

        Integer i1 = new Integer(10);

        System.out.println(i == i1);

}

true

Integer和int比较会进行自动拆箱,比较的是大小

2.Integer和Integer比较大小

public static void main(String[] args) {

        Integer i =new Integer(10);

        Integer i1 = new Integer(10);

        System.out.println(i == i1);

}

false

Integer 直接等于数字如果在-128到127之间会保存到常量池,而直接new出来的是对象,所以不相等

public static void main(String[] args) {

        Integer i = 10;

        Integer i1 = 10;

        System.out.println(i == i1);

}

true

public static void main(String[] args) {

        Integer i = 128;

        Integer i1 = 128;

        System.out.println(i == i1);

}

false

通过测试发现,第一个数据输出i1==i1,第二个数据输出i1!=i1.
原因是因为
在给Integer赋值时,实际上是自动装箱的过程,也就是调用了Integer.valueOf(int)方法,当这个值大于等于-128并且小于等于127时使用了常量池,所以前两个地址是相等的,但是后两个超过了127,故不使用常量池。

也就是说
Integer -128~127实际上你可以看成是整形int,所以第一个类的输出结果应该是==
Interger 128以上的数值就不能看成int了,他是对象,两个值相同的不同的对象如果用==判断肯定是不等的,可以用equals判断。
 

猜你喜欢

转载自blog.csdn.net/u011136197/article/details/82111175