Java除了基本类型外,所有类都继承至Object,其中Object有个方法:
public native int hashCode();
此方法用于让对象产生一个哈希值,每个类可自行实现此方法
那么Hash,音译叫哈希,大学上课叫散列函数,简单概括是一种不一定唯一的压缩映射概念
以字符串举例,将一个很长的字符串变成一个较小的值用于两者映射
不一定唯一,是说a1和a2不相等,但是hash(a1)和hash(a2)可能相等,因为算法不一样
为什么说它是一种概念,因为它没有固定的公式,公式可以自定义
在Java中,String类的hash算法如下(JDK提供的Arrays.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(i) = hash(i-1) * 31 + val[i];将字符串的逐字符迭代乘以31
例如String str = "abcd";
第1次循环:hash = 'a'
第2次循环:hash = 31 * 'a' + 'b'
第3次循环:hash = 31 * (31 * 'a' + 'b') + 'c'
第4次循环:hash = 31 * (31 * (31 * 'a' + 'b') + 'c') + 'd'
Time33算法,是从《大型网站技术架构》一书中章节4.3.4中第3点数据结构中有提到,Time33能较好的解决冲突,笔者对此部分尚未深究,后续可以去找一些文献看一下原因
此算法和jdk中一致,只是值不一样,jdk是31,书中描述是33,一个是2^6-1,另一个是2^6+1,直觉上差不得
哈希值在java中如hashmap中就有使用,通过table的容量和key的hash值的&,算出所在的下标,再配合红黑树(TreeNode)达到快速查找元素
key的hash函数在HashMap类中
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
在放入元素时,核心代码 tab[i = (n - 1) & hash]
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
// 核心点在此处,hash不冲突的场景下
tab[i] = newNode(hash, key, value, null);
else {
// hash冲突时,则通过树进行处理
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
在获取元素时
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
// 首先此处得先根据hash能匹配到
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
hashmap扩容和红黑树查找就先不说了
通过hash算法就能很大程度上将map中存储的数据通过一次就查找到(当然幢号的情况下,还需要在红黑树里再找一下)
其余的例如MD5、SHA等都属于哈希算法范畴,只是各自的实现的业务场景不一样而已,hashmap中通过哈希能大概率不一致且性能高,占用空间小;MD5基本上可以说不会重复,但是相比较性能差,所以哈希算法在应用过程中,还是要看自身场景去决定算法具体如何去写更合适