"SCJP 1.6版考題 200" 修訂間的差異
(新頁面: Given: <br>11. public class Person{ <br>12. private String name; <br>13. public Person(String name){ <br>14. &n...) |
(無差異)
|
於 2013年3月27日 (三) 17:05 的最新修訂
Given:
11. public class Person{
12. private String 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 statement 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.
解答
Ans: B
解說:
B. A HashSet could contain multiple Person objects with the same name.
HashSet不會有重複的元素,但前題類別必須重寫hashCode與equals提供元素間的比較方法
Person類別只提供equals方法,沒有提供hashCode方法…
二個物件會先用hashCode()方法傳回的值是否相同,如果相同,則再使用equals()方法比較,如果兩者都相同,則視為相同的物件。
|