什么是哈希
Hash也称散列、哈希,对应的英文都是Hash。基本原理就是把任意长度的输入,通过Hash算法变成固定长度的输出. 所以问题的关键在于什么样的算法这么神奇呢? 能把任意长度的东西变成固定长度的输出呢?
为什么需要哈希?
比如判断内容是否相同.直接比较可能耗时比较长.
比如密码验证,因为哈希是不可逆的,网站只存储密码计算出来的哈希值. 当你登录时,再次计算哈希值比对就行了. 直接存储密码是很危险的.
哈希算法有哪些实现?
md5,sha
哈希算法有哪些不足?
哈希碰撞.
若不同的原始数据被有损压缩后产生了相同的结果,该现象称为哈希碰撞。哈希碰撞的产生概率能衡量一个哈希算法的优劣。
java中哈希的应用
比如hashmap中key的唯一性保证.
再java的祖宗类Object中,就有哈希的身影.
public native int hashCode();
不同的类有不同的实现,比如String类中的实现如下
看注释hash的计算公式为
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
如果hash为0并且字符串长度不为0才计算hash,为什么为0 才计算呢?因为hash默认值为0,为0说明没计算过.要是计算过直接用以前的就好了.
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;
}
/** Cache the hash code for the string */
private int hash; // Default to 0
测试一下
System.out.println("1".hashCode());//49
在interger中实现如下,也就是说,整数的hashCode定义为其自身.
public static int hashCode(int value) {
return value;
}
测试
System.out.println(Integer.hashCode(123));//123
再比如Double类型的hashCode方法
public static int hashCode(double value) {
long bits = doubleToLongBits(value);
return (int)(bits ^ (bits >>> 32));
}
Idea自动生成HashCode方法
当你自定义一个类时,往往要自定义hashCode方法和equals方法,此时可以用idea自动生成,比如
最终效果如下
class Student{
private String name;
private int age;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age &&
Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
自动生成hashCode方法中的Objects类是个工具类,和Object类不同,不要混淆.