Given:
11. public class Person {
12. private name;
13. public Person(String name) {
14. this.name = name;
15. }
16. public boolean equals(Object o) {
17. if( !o instanceof Person ) return false;
18. Person p = (Person) o;
19. return p.name.equals(this.name);
20. }
21. }
Which is true?
A. Compilation fails because the hashCode method is not overridden.
B. A HashSet could contain multiple Person objects with the same
name.
C. All Person objects will have the same hash code because the
hashCode method is not overridden.
D. If a HashSet contains more than one Person object with
name=”Fred”, then removing another Person, also with name=”Fred”,
will remove them all.

解决方案 »

  1.   

    因为其它的答案是错的,Person对象加入HashSet时是作为value而不是key,当然想怎么放就怎么放
      

  2.   

    Sorry,想成Map了,刚才的回答收回
      

  3.   

    Person 只是重写了equals的方法,没有重写hashCode()的方法,所以即使有多个相同名字的Person对象,他们的hashCode()仍然不一样,所以HashSet允许他们同时存在, B 正确
      

  4.   

    这个问题的关键在于HashSet判断两个对象相同时,是用hashCode()相等进行判断,还是调用对象的equals(Object)方法。虽然之前我不知道,但是根据答案可以反推,HashSet是用前一种方式判断的。A答案不正确,因为Person可以不重写hashCode()方法。当类没有重写hashCode()方法时,同一个类的两个对象调用hashCode()返回的值应该是不同的(可以查查JAVA DOC)。和name属性应该是没有关系的……所以答案C、D是错的……
      

  5.   

    应该是先比较hashCode(),然后用equals()比较。
      

  6.   

    英语不太好,但是程序的12句没定义name的类型
      

  7.   

    HashSet内部使用HashMap管理对象,添加对象到HashSet时,是将对象作为内部HashMap的key进行处理,若发现已存在hashCode相同且equals比较结果为true的对象,就认为该key已经存在,返回HashMap中的旧对象回来,而多个Person对象有不同的hashCode,因此全可以被加入到HashSet此外你的代码有多处错误,估计是笔误
      

  8.   

    支持一下三楼 V_Naga(那加)
    没有重写hashCode()方法,hashCode()仍然返回由内存地址生成的一个整数,new了不同的对象,其值也不同,就可以放进hashset了
    ps:楼主是不是贴的不全啊,定义name前的String,还有if( !o instanceof Person ) return false;是不是应该为if( !(o instanceof Person )) return false;?
    A选项如果去掉because后面的就对了,呵呵