Given:1. public class Person{
2. private String name;
3. public Person(String name){this.name = name;}
4. public boolean equals(Person p){
5. return p.name.equals(this.name);
6. }
7. }
Which statement is true?A. The equals method does NOT properly override the Object.equals method.
B. Compilation fails because the private attribute p.name cannot be accessed in line 5.
C. To work correctly with hash-based data structures, this class must also implement the hashCode method.
D. When adding Person objects to a java.util.Set collection, the equals method in line 4 will prevent duplicates.
请问应该选哪个,不对的错在哪里。多谢。
2. private String name;
3. public Person(String name){this.name = name;}
4. public boolean equals(Person p){
5. return p.name.equals(this.name);
6. }
7. }
Which statement is true?A. The equals method does NOT properly override the Object.equals method.
B. Compilation fails because the private attribute p.name cannot be accessed in line 5.
C. To work correctly with hash-based data structures, this class must also implement the hashCode method.
D. When adding Person objects to a java.util.Set collection, the equals method in line 4 will prevent duplicates.
请问应该选哪个,不对的错在哪里。多谢。
C:没写,就会调用默认的父类hashCode方法
D:由于不是重写equals方法,所以不会调用该方法
这个里面详细介绍,希望对楼主有帮助
不过C的错误和6楼理解不太一样,如果不重写hashCode回调用父类Object的hashCode方法,但这个就不能算是work correctly了吧,我的理解是,他连equals都没重写好,这条直接免谈了……
equals怎么重写完全看你的需要
试了一下,确实可以,private定义记不清楚了,受教受教,谢谢,呵呵
B 不对,当前类能访问private的属性
C 可以重写也可以不重写,不重写会调用父类的,只是效率差点
D 当往set中加入的时候并不会使用此equals方法,会调用父类的equals方法,因为该方法没有被重写
因为Person根本没重写object中的equals方法
所以加入hashset时候,还是调用的objectequals方法
代码测试过如下
main方法
public static void main(String ... args) throws Exception {
HashSet s=new HashSet();
System.out.println(s.add(new Person("name")));
System.out.println(s.add(new Person("name")));
}
person类 class Person {
private String name; public Person(String name) {
this.name = name;
} public boolean equals(Person p) {
return true;
} @Override
public int hashCode() {
return name.hashCode();
}
}结果是
true
true
如果把public boolean equals(Person p) {
return true;
}改成public boolean equals(Object p) {
return true;
}
那么是
true
false
测试证实了上述我的判断
哈希检索的两个步骤:
1、使用hashCode()找到正确的位置,或者称之为桶吧,因为里面有可能有多个元素
2、使用equals()在该桶内找到正确的元素。
The access level can't be more restrictive than the overriden method's.
访问修饰符可以大于或等于被重写方法的访问修饰符。thx。
class Person {
private String name; public Person(String name) {
this.name = name;
} public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (this.getClass() != obj.getClass())
return false;
Person p = (Person) obj;
return name.equals(p.name);
}
public int hashCode() {
return name.hashCode();
}
}
如果将可变对象用作 set 元素,那么必须极其小心。如果对象是 set 中某个元素,以一种影响 equals 比较的方式改变对象的值,那么 set 的行为就是不确定的。此项禁止的一个特殊情况是不允许某个 set 包含其自身作为元素。