亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用語法,關于equals()方法和“==”區別?如下情況

使用語法,關于equals()方法和“==”區別?如下情況

慕容708150 2021-05-18 18:11:44
public class TestHashCode {public static void main(String[]args){int i=5,j=5;System.out.println(i==j);Person p1=new Person(0);Person p2=new Person(0);if(p1==p2){System.out.println("p1==p2");}else {System.out.println("p1!=p2");}if(p1.equals(p2)){System.out.println("p1 is equals to p2");}else{System.out.println("p1 is not equals to p2");}p2=p1;System.out.println(p1==p2);System.out.println(p1.equals(p2));}}equals()比較內容 “==”比較地址,為什么p1.equals(p2)為false 呢?
查看完整描述

2 回答

?
慕桂英3389331

TA貢獻2036條經驗 獲得超8個贊

對于Person類的2個實體化對象P1與P2來說,他們被new出來后,占用的是不同的存儲單元的,所以他們的地址并不相同,因此p1.equals(p2)為false 。
如果需要返回的結果為true,你必須重寫equals方法。
例如在Person類里面重寫equals方法(假設Person里面成員變量i的值相等就可以認為兩個對象相等):
public boolean equals(Person p) {
if(this.i == p.i) {
return true;
} else {
return false;
}
}
}

查看完整回答
反對 回復 2021-05-23
?
茅侃侃

TA貢獻1842條經驗 獲得超21個贊

equals 和 == 的區別
*
* @author FlyFive([email protected])
* created on 2013-1-5
*/
public class EqualsTest {
public static void main(String[] args) {
String s01 = new String("hello world");
String s02 = new String("hello world");
System.out.println("兩個new出來的String");
System.out.println(s01.equals(s02));
System.out.println(s01 == s02);
String s11 = new String("hello world");
String s12 = s11;
System.out.println("兩個相同的String");
System.out.println(s11 == s12);
System.out.println(s11 == s12);

String s21 = "hello world";
String s22 = "hello world";
System.out.println("兩個直接賦值的String");
System.out.println(s21.equals(s21));
System.out.println(s21 == s22);
Object s31 = new Object();
Object s32 = new Object();
System.out.println("兩個new出來的普通對象");
System.out.println(s31.equals(s31));
System.out.println(s31 == s32);
Integer s41 = new Integer(1);
Integer s42 = new Integer(1);
System.out.println("兩個new出來的基本類型包裝類");
System.out.println(s41.equals(s41));
System.out.println(s41 == s42);
}
}



查看完整回答
反對 回復 2021-05-23
  • 2 回答
  • 0 關注
  • 523 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號