我有些困惑,因为在面试中问到了这个问题,我回答说:“每当创建堆中的一个对象时,就会为该对象生成hashCode。”
但是面试官说:“只有在调用对象的hashcode方法时才会生成它。”
此外,我希望更深入地了解关于Java中的hashcode,可以分享一些链接/资源,因为在一些工作面试中经常被问到。
PS: 当我对一个对象进行sysout时,输出结果为employee@942f533。
这取决于你的意思。正如其他答案所提到的,当你创建函数时,函数本身并不会被调用。然而,
90 * As much as is reasonably practical, the hashCode method defined by
91 * class {@code Object} does return distinct integers for distinct
92 * objects. (This is typically implemented by converting the internal
93 * address of the object into an integer, but this implementation
94 * technique is not required by the ... [JDK]
来自http://www.docjar.com/html/api/java/lang/Object.java.html
由于对象的地址在创建时被分配,所以从某种意义上说,您是正确的。但是,由于它不是必需的,并且许多对象定义了重写,因此并非所有对象都是如此。通常在面试中,您需要挑战面试官,以便更好地描述您的意思。如果您这样做并且是正确的,则问题解决了;如果您这样做并且错误,则至少表明您比原始陈述所显示的更深入地理解了问题。
实际上,你需要理解哈希码的使用才能理解。
哈希码不是在对象创建时生成的,而是在调用hashCode()方法时生成的。
对于每个对象,您可能不想重写java.lang.Object的默认哈希码实现。它实际上是所有内部使用哈希算法的类所必需的。例如HashMap、HashSet等。如果您查看这些方法的内部实现,您会发现哈希码的使用等。
来自java.util.HashMap的代码片段:
public V get(Object key) {
if (key == null)
return getForNullKey();
int hash = hash(key.hashCode());
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
return e.value;
}
return null;
}
正如您所看到的,它用于从数据结构中获取正确的对象。
如果您检查对象哈希码的注释,它也清楚地提到了这一点。
* Returns a hash code value for the object. This method is
* supported for the benefit of hashtables such as those provided by
* <code>java.util.Hashtable</code>.
hashcode()是像其他方法一样的方法。它不会在对象创建时被调用,但当您将对象放入映射中时可能会被调用。
我认为应该阅读的第一个文档是:http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode()