Java hashcode是在调用hashcode()方法时生成的
当我在采访中被问到这个问题时,我有点困惑,我说:“hashCode是在当前运行的应用程序的堆上创建时为每个对象生成的” 但采访中说:“它是在我们调用对象上的hashcode方法时生成的” 此外,我希望更深入地理解hashcode(对java来说也是wrt),请分享一些链接/源代码,因为在一些面试中会广泛地询问这些链接/源代码 PS:当我在一个对象上执行sysout…时,输出如下employee@942f533hashcode()方法与任何其他方法一样。创建对象时不会调用它,将对象放入地图时可能会调用它Java hashcode是在调用hashcode()方法时生成的,java,hashcode,Java,Hashcode,当我在采访中被问到这个问题时,我有点困惑,我说:“hashCode是在当前运行的应用程序的堆上创建时为每个对象生成的” 但采访中说:“它是在我们调用对象上的hashcode方法时生成的” 此外,我希望更深入地理解hashcode(对java来说也是wrt),请分享一些链接/源代码,因为在一些面试中会广泛地询问这些链接/源代码 PS:当我在一个对象上执行sysout…时,输出如下employee@942f533hashcode()方法与任何其他方法一样。创建对象时不会调用它,将对象放入地图时可能会
我认为首先要阅读的文档应该是:()这取决于您在这里的意思。正如其他答案所提到的,创建函数时不会调用函数本身。但是,
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]
从
由于对象的地址是在创建时指定的,因此您在某种意义上是正确的。但是,由于它不是必需的,而且许多对象定义了覆盖,所以它不一定适用于所有对象
通常在面试中,你必须挑战面试官一点来描述你的意思。如果你这么做了,问题就解决了,如果你这么做了,你错了,那么你至少表明你比你原来的陈述有更深的理解。实际上,你需要理解哈希代码的用法才能理解 Hashcode不是在对象创建时生成的,而是在调用Hashcode()时生成的。 对于每个对象,您可能不希望覆盖java.lang.object哈希代码的默认实现。实际上,所有在内部使用哈希算法的类都需要它。e、 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;
}
感谢您的回复…我知道创建对象时不会调用hashcode(),但我的问题有点不同。hashcode(值)是在heap+1中创建新对象时计算的吗:对于String,hashcode会被缓存,因此每个对象只生成一次(并重新使用),除非hashcode为0;)
* 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>.