hashCode
public class Object {
public native int hashCode(); // 是Object对象的方法,有默认实现,但是native的。由内存地址计算而来。
}
所有
的类要么重写hashCode方法,要么调用Object的hashCode()方法。
public class _hashCodeTest {
public static void main(String[] args) {
System.out.println(new Integer(10).hashCode());//数字,返回自身 10
System.out.println(new Integer(-10).hashCode());//数字,返回自身 -10
System.out.println(new Boolean(true).hashCode());//1237
System.out.println(new Boolean(false).hashCode());//1231
System.out.println("5".hashCode()); // 字符串 53
System.out.println("50".hashCode()); //字符串 1691
System.out.println(new Student().hashCode());// 自定义1314
System.out.println(new _hashCodeTest().hashCode()); //没有自定义,对象的内存地址计算而来
}
}
class Student {
@Override
public int hashCode() {
return 1314;
}
}
Integer:
public final class Integer extends Number implements Comparable<Integer> {
private final int value;
public Integer(int value) {
this.value = value;
}
@Override
public int hashCode() {
return Integer.hashCode(value);
}
//返回自身的值
public static int hashCode(int value) {
return value;
}
}
Long类型:
public final class Long extends Number implements Comparable<Long> {
//1 保证了 如果value在int范围内,则hash值不变
public static int hashCode(long value) {
return (int)(value ^ (value >>> 32)); // 如果在int范围内,则高位的32位都是0, 通过无符号右移32位后,变为0
// 和原来的值做异或运算.(两个操作数的位中,相同则结果为0,不同则结果为1).
}
@Override
public int hashCode() {
return Long.hashCode(value);
}
}
Boolean:
public final class Boolean implements java.io.Serializable,
Comparable<Boolean> {
@Override
public int hashCode() {
return Boolean.hashCode(value);
}
//返回固定的值。true:1231 false:1237 , 为什么是这两个数
public static int hashCode(boolean value) {
return value ? 1231 : 1237;
}
}
String类型:
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
public int hashCode() {
int h = hash;
//1 hash作为一个成员, 每次调用hashCode(), 都检查h == 0,优化性能,避免重复计算
if (h == 0 && value.length > 0) {
char val[] = value;
//2 遍历整个字符数组
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i]; //3 字符就是整数
}
hash = h;
}
return h;
}
}