public class Person{
private String name;
public Person(String name){this.name=name;}
public boolean equals(Person p){
return p.name.equals(this.name)
}
}A.the equals method does not properly override the object.equals method;
B.complilation fails because the private attribute p.name cannot be accessed in line 5;
C.to work correctly with hash-base date structures,this class must also implement the hashcode method;
D.when adding person object to java.util.set collection,the equals method in line 4 will prevent duplicates.
private String name;
public Person(String name){this.name=name;}
public boolean equals(Person p){
return p.name.equals(this.name)
}
}A.the equals method does not properly override the object.equals method;
B.complilation fails because the private attribute p.name cannot be accessed in line 5;
C.to work correctly with hash-base date structures,this class must also implement the hashcode method;
D.when adding person object to java.util.set collection,the equals method in line 4 will prevent duplicates.
The correct way to override it is as follows.public boolean equals(Object o) {
return (o instanceof Person) && ((Person)o).name.equals(this.name);
}
override requires the same parameters
so the answer is A
if(this == o) return true;
if(o == null) return false;
if(!this.getClass().getName().equals(o.getClass().getName())) return false;
Person p = (Person)o;
if(this.name.equals(p.name)) return true;
else return false;
}
Java语言规范要求equals方法满足以下特点:
1、自反性,2、对称性,3、传递性,4、一致性,5、对任意非空引用x,x.equals(null)应当返回false
上面的语句应该违反了对称性,如果x.equals(y),y.equals(x)也应该是成立的,但是如果上面的person p是person的子类对象,则equals返回就不是true了,所以重载不正确……
if(this == o) return true;
if(o == null) return false;
if(!this.getClass().getName().equals(o.getClass().getName())) return false;
Person p = (Person)o;
if(this.name.equals(p.name)) return true;
else return false;
}
if(!this.getClass().getName().equals(o.getClass().getName())) return false;
--------------------------
这句难道没问题吗?