2 回答

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;
}
}
}

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);
}
}
添加回答
舉報