标签:style http color io os java ar for 2014
11. public class Person {
12. private String name, comment;
13. private int age;
14. public Person(String n, int a, String c) {
15. name = n; age = a; comment = c;
16. }
17. public boolean equals(Object o) {
18. if (! (o instanceof Person)) return false;
19, Person p = (Person)o;
20. return age == p.age && name.equals(p.name);
21. }
22. }
What is the appropriate definition of the hashCode method in class Person?
A. return super.hashCode();
B. return name.hashCode() + age * 7;
C. return name.hashCode() + comment.hashCode() / 2;
D. return name.hashCode() + comment.hashCode() / 2 - age * 3;
Answer: B
hashCode
public int hashCode()
Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by HashMap.
返回一个对象的hash code值。这个方法被用在hash tables中,例如HashMap
The general contract of hashCode is:
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)
实际上,由 Object 类定义的 hashCode 方法确实会针对不同的对象返回不同的整数。一般是通过将该对象的内部地址转换成一个整数来实现的
Returns:
a hash code value for this object.
See Also:
equals(java.lang.Object), System.identityHashCode(java.lang.Object)
题目分析:
很明显hashcode跟equals有关,这里重写了equals,解读这个equals()发现是根据年龄和名字来判断是否相同的。只要名字和年龄相同了,hashcode返回整数就相同。
首先是C和D:有个comment在里面,不符合上equals()的条件,不行。
然后A、B:根据“由 Object 类定义的 hashCode 方法确实会针对不同的对象返回不同的整数。”,A对不同对象产生相同的hashCode返回值。所以A错。
答案B
对hashcode()的解读转自http://www.th7.cn/Program/java/201404/189079.shtml
标签:style http color io os java ar for 2014
原文地址:http://www.cnblogs.com/wjcom/p/3970740.html