equals and '=='

public static void main(String[] args) {
Integer i=1;
Integer j=1;
System.out.println(i==j);
System.out.println(i.equals(j));
Integer i1=128;
Integer j1=128;
System.out.println(i1==j1);
System.out.println(i1.equals(j1));
int i2=1;
int j2=1;
System.out.println(i2==j2);
int i3=128;
int j3=128;
System.out.println(i3==j3);
}

以上输出结果是什么呢?

true
true
false
true
true
true

那么为什么第三个输出是false呢

在给Integer赋值时,实际上是bai自动装箱的过程,也就是调用了Integer.valueOf(int)方法,当这du个值大zhi于等于-128并且小于等于127时使用了常量池,所以前两个地址是相等的,但是后两个超过了127,故不使用常量池。

posted @ 2020-11-09 10:17  IAmSao瑞  阅读(85)  评论(0)    收藏  举报