做了equals为什么没有 object ok! 的显示,为什么p1 和p2不相等?
class testperson
{
public String name;
public int age;
public testperson(String name,int age)
{
this.name=name;
this.age=age;
System.out.println("done!");
}
public static void main(String [] args)
{
testperson p1=new testperson("aaa",20);
testperson p2=new testperson("aaa",20);
if(p1.equals(p2))
System.out.println("object ok!");
String a=new String ("eee");
String b=new String ("eee");
if(a.equals(b))
System.out.println("string ok!");
}}
class testperson
{
public String name;
public int age;
public testperson(String name,int age)
{
this.name=name;
this.age=age;
System.out.println("done!");
}
public static void main(String [] args)
{
testperson p1=new testperson("aaa",20);
testperson p2=new testperson("aaa",20);
if(p1.equals(p2))
System.out.println("object ok!");
String a=new String ("eee");
String b=new String ("eee");
if(a.equals(b))
System.out.println("string ok!");
}}
public boolean equals(testperson t){
if(this.name.equals(t.name) && this.age==t.age){
return true;
}else{
return false;
}
}
testperson p2=p1;//p1和p2指向了同一个对象这个时候比较就相等了
其他的一般只要重写equals()方法即可:-)
p1.equals(p2)默认调用的是object的equals方法,此方法是比较两个对象的内存地址,因为不相等,所以不会打印"object ok"。
string的equals方法是个特例,它比较的是两个对象的具体内容.
if(this.name == t.name && this.age==t.age)
之所以可以改成这样,是因为你传的实参“aaa”是在String池中创建的,而不是在堆中创建的一个String对象。
public boolean equals(Object obj) {
return (this == obj);
}//String.equals()
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}