我有点困惑,因为在一次采访中被问到这个问题,我说:““在当前运行的应用程序的堆上创建每个对象时,都会为每个对象生成哈希码””
但采访说:“它是我们在对象上调用hashcode方法时生成的”
此外,我希望更深入地了解哈希码(这对 java 来说也是如此),请分享一些链接/资源,因为它在一些工作面试中被广泛询问
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 ()