日期:2014-05-20  浏览次数:20780 次

为什么答案是B,
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.


------解决方案--------------------
因为其它的答案是错的,Person对象加入HashSet时是作为value而不是key,当然想怎么放就怎么放
------解决方案--------------------
Person 只是重写了equals的方法,没有重写hashCode()的方法,所以即使有多个相同名字的Person对象,他们的hashCode()仍然不一样,所以HashSet允许他们同时存在, B 正确
------解决方案--------------------
关注
------解决方案--------------------
这个问题的关键在于HashSet判断两个对象相同时,是用hashCode()相等进行判断,还是调用对象的equals(Object)方法。

虽然之前我不知道,但是根据答案可以反推,HashSet是用前一种方式判断的。

A答案不正确,因为Person可以不重写hashCode()方法。

当类没有重写hashCode()方法时,同一个类的两个对象调用hashCode()返回的值应该是不同的(可以查查JAVA DOC)。和name属性应该是没有关系的……

所以答案C、D是错的……
------解决方案--------------------
应该是先比较hashCode(),然后用equals()比较。
------解决方案--------------------
英语不太好,但是程序的12句没定义name的类型
------解决方案--------------------
原来有这么多高手啊 而且英语都特别好
我都看不太懂
------解决方案--------------------
支持一下三楼 V_Naga(那加)
没有重写hashCode()方法,hashCode()仍然返回由内存地址生成的一个整数,new了不同的对象,其值也不同,就可以放进hashset了
ps:楼主是不是贴的不全啊,定义name前的String,还有if( !o instanceof Person ) return false;是不是应该为if( !(o instanceof Person )) return false;?
A选项如果去掉because后面的就对了,呵呵