int的哈希码

Ed *_*Lee 23 java int primitive hashcode

什么是基本类型的哈希码,例如int?

例如,让我们说num是一个整数.

int hasCode = 0;

if (num != 0) {
  hasCode = hasCode + num.hashCode();
}
Run Code Online (Sandbox Code Playgroud)

Kon*_*che 40

取自Integer.class源代码:

/**
 * Returns a hash code for this {@code Integer}.
 *
 * @return  a hash code value for this object, equal to the
 *          primitive {@code int} value represented by this
 *          {@code Integer} object.
 */
public int hashCode() {
    return value;
}
Run Code Online (Sandbox Code Playgroud)

value整数的值在哪里.


Mar*_*nik 37

对于hashCode一个int最自然的选择是使用它int自己.一个更好的问题是什么用于hashCodea,long因为它不适合int-sized哈希码.这个以及所有hashCode相关问题的最佳来源是Effective Java.

  • 我对`long`哈希代码感到好奇并且查了一下,它是:`(int)(value ^(value >>> 32));` (13认同)
  • @MarkoTopolnik为什么*不会*__实现Java API ___提及__Java API__如何工作... grepcode只包含上传的OpenJDK版本,所以实际上你正在提倡我刚刚做的事情.除此之外,检查[`Integer.hashCode`]的规范(http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#hashCode())和[`Long .hashCode`](http://docs.oracle.com/javase/7/docs/api/java/lang/Long.html#hashCode())实际上是学习这个的最佳选择.所有实现都必须符合规范. (3认同)

kos*_*osa 9

没有hashCode()原始类型的方法int可用.

Integer是Wrapper类类型并hashcode()返回一个int