Java基本类型包装类的hashCode方法,Integer、String...
hashCode方法含义
hash值在java中是一个int类型,主要用来在散列存储结构中确定对象的位置,一个好的hashCode方法应该尽量保证应尽量保证对象hash值分布的均匀性,同时减少重复hash值的出现。
Integer中的hashCode方法实现
public static int hashCode(int value) { return value; }
Integer的hashCode方法实现比较简单,直接以对应的int值作为hash值。
String中的hashCode方法实现
public int hashCode() { int h = hash; if (h == 0 && value.length > 0) { char val[] = value; for (int i = 0; i < value.length; i++) { h = 31 * h + val[i]; } hash = h; } return h; }
上面代码中的hash的定义(hash值),value的定义(String对应的char数组):
/** Cache the hash code for the string */ private int hash; // Default to 0 private final char value[]; public String(String original) { this.value = original.value; this.hash = original.hash; }
这里的h变量先等于了hash,首先判断hash是否等于0,如果不等于0说明它的hash值不需要再计算一遍了(已经在构造函数中获取了),同时查询ASCII码表知道,null对应的ASCII值为0,显然这也符合hash初始为0的设置(即初始Sting == null)。h不等于0且字符串不为空才执行计算操作,说明空字符串对应的hash值也为0。 计算方式为:val[0]*31^(n-1) + val[1]*31^(n-2)… + val[n-1],使用素数31相乘产生的hash值的重复的概率更小。
Long中的hashCode方法实现
public static int hashCode(long value) { return (int)(value ^ (value >>> 32)); }
通俗的讲就是将long的前32位与后32位进行异或后得到hash值。
Double中的hashCode方法实现
public static int hashCode(double value) { long bits = doubleToLongBits(value); return (int)(bits ^ (bits >>> 32)); }
类似于Long中的实现方法。
Chracter中的hashCode方法实现
public static int hashCode(char value) { return (int)value; }
Character中的hashCode方法返回字符对应的ASCII值。
Boolean中的hashCode方法实现
public static int hashCode(boolean value) { return value ? 1231 : 1237; }
value为true时对应1231,为false时对应1237。
Boolean中的hashCode方法实现
public static int floatToIntBits(float value) { int result = floatToRawIntBits(value); // Check for NaN based on values of bit fields, maximum // exponent and nonzero significand. if ( ((result & FloatConsts.EXP_BIT_MASK) == FloatConsts.EXP_BIT_MASK) && (result & FloatConsts.SIGNIF_BIT_MASK) != 0) result = 0x7fc00000; return result; }
floatToRawIntBits(value)是一个native方法,具体实现没看,直观的看即是Float对象的hash值等于 函数 floatToRawIntBits返回的值。