我有点困惑,因为这个问题是在一次面试中被问到的,我说过:“在当前运行的应用程序中的堆上创建每个对象时,都会为其生成hashCode。”
但采访中说:“它是我们在对象上调用hashcode方法时生成的。”
此外,我希望能更深入地了解哈希码(以及wrt到java),请分享一些链接/来源,因为它在一些工作面试中被广泛询问
PS:当我使用sysout...on对象时,输出是employee@942f533
发布于 2012-05-07 12:08:54
这取决于你在这里的意思。正如其他答案所提到的,函数本身在您创建它时不会被调用。然而,
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
由于对象的地址是在创建时分配的,因此在某种意义上您是正确的。但是,由于它不是必需的,而且许多对象都定义了覆盖,因此不一定对所有对象都是如此。
通常在面试中,你必须向面试官提出一点挑战,以描述你的意思。如果你这样做了,你是对的,问题就解决了,如果你这样做了,你错了,那么你至少已经证明了你比你最初的陈述显示出了更深刻的理解。
发布于 2012-05-07 12:06:19
hashcode()方法和其他方法一样。它不会在对象创建时被调用,它可能会在您将对象放入map中时调用。
我认为首先要阅读的文档应该是:http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode()
发布于 2012-05-07 13:27:31
实际上,您需要了解哈希码的用法才能理解。
哈希码不是在创建对象时生成的,而是在调用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>. https://stackoverflow.com/questions/10476491
复制相似问题