Java中的==和equals的区别,以及int中的常量池存储

2021-05-30  本文已影响0人  只会吹水的程序员

public static void main(String[] args) {
boolean resultA = StringTest.equalsObj("a", "A");
boolean resultB = StringTest.equalsObj("a", "a");
boolean resultC = StringTest.equalsObj("a", new StringBuffer("a"));
System.out.println("resultA" + resultA);
System.out.println("resultB" + resultB);
System.out.println("resultC" + resultC);
StringBuffer variableA = new StringBuffer("A");
StringBuffer variableA2 = new StringBuffer("A");
System.out.println(System.identityHashCode(variableA));
System.out.println(System.identityHashCode(variableA2));
String a = "a";
String a2 = "a";
System.out.println(System.identityHashCode(a));
System.out.println(System.identityHashCode(a2));
System.out.println("resultD" + variableA.equals(variableA2));
/*总结
* ==是比较两个对象的地址
* equals如果对象不是string的类型的话就比较地址否则利用while循环来一个一个的比较他们的字符是否相等
* /
Integer variableOne = -128;
Integer variableTwo = -128;
System.out.println("####################");
System.out.println(System.identityHashCode(variableOne));
System.out.println(System.identityHashCode(variableTwo));
//结果是true
Integer variableThree = -129;
Integer variableFour = -129;
System.out.println(System.identityHashCode(variableThree));
System.out.println(System.identityHashCode(variableFour));
//结果是false
Integer variableFive = 127;
Integer variableSix = 127;
System.out.println("#######127######");
System.out.println(System.identityHashCode(variableFive));
System.out.println(System.identityHashCode(variableSix));
//结果相等
System.out.println("########128#######");
Integer variableSev = 128;
Integer variableEig = 128;
System.out.println(System.identityHashCode(variableSev));
System.out.println(System.identityHashCode(variableEig));
//结果不相等
int aaa = 129;
int bbb = 129;
System.out.println("#####129#####");
System.out.println(System.identityHashCode(aaa));
System.out.println(System.identityHashCode(bbb));
//结果不相等
/
总结
* 无论是int还是Integer 他们的常量池存储的范围是[-128,127]
* 如果在范围之类,他们的地址是一样的,如果超出了常量池的范围,则他们的这个值会存储在不同的堆内存中
* */
}

image.png
上一篇下一篇

猜你喜欢

热点阅读