HashMap与HashTable原理及数据结构

hash表结构个人理解

hash表结构,以计算出的hashcode或者在hashcode基础上加工一个hash值,再通过一个散列算法 获取到对应的数组地址映射.然后将值存储到该映射地址上,存储所在的集合称为hash表

hash表结构 散列法:元素特征转变为数组下标的方法。

散列法:元素特征转变为数组下标的方法 就是个人理解里边对散列法的概括

网上找的一些散列法:

1,除法散列法 (取余法) 
最直观的一种,使用的就是这种散列法,公式:  
index = value % 16  
学过汇编的都知道,求模数其实是通过一个除法运算得到的,所以叫“除法散列法”。

2,平方散列法  
求index是非常频繁的操作,而乘法的运算要比除法来得省时(对现在的CPU来说,估计我们感觉不出来),所以我们考虑把除法换成乘法和一个位移操作。公式:  
h=h >> 12; (无符号右移,除以2^12。记法:左移变大,是乘。右移变小,是除。) 
如果数值分配比较均匀的话这种方法能得到不错的结果

3, 折叠法:将keyword切割成位数同样的几部分,最后一部分位数能够不同,然后取这几部分的叠加和(去除进位)作为散列地址 
4, 直接寻址法:取keyword或keyword的某个线性函数值为散列地址。即H(key)=key或H(key) = a•key + b,当中a和b为常数(这样的散列函数叫做自身函数) 
这几个算法没有再细研究,但归纳起来就是让hash值通过这散列算法获取更优的映射

HashMap和HashTable的数据结果


如图1: 
hash表结构:左侧是hash表,右侧是单链表Entry

HashMap与HashTable相同点

1.二者都是以哈希表数据结构存储数据. 
2.二者都是以链表来作为解决冲突方案:由于不同的对象最终获取的hash值可能一致,这时候就会在该hash表所对应的链表的头结点插入这个键值对. 
3.二者都可以进行数组扩容

HashMap与HashTable异同点

1.是否可以存储null key,null value不同:HashMap可以存储null key和null值,HashTable则不允许会报异常,请看(1.1)put调用允许null(1.2)HashTable value为null报错(1.3)HashTable key调用hash会空指针异常的区别 
HashMap部分源码:

    public class HashMap{
//(1.1)put的方法调用putForNullKey(k)方法
public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
if (key == null)
//(1.1)实际key为null时执行的方法
return putForNullKey(value);//可以调用key为null的情况,而且value也没有限制
int hash = hash(key);
int i = indexFor(hash, table.length);
//(1.2)如果key一致则替换原先的value
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
} modCount++;
//(2.1)如果key不一致时执行的方法
addEntry(hash, key, value, i);
return null;
}
//(1.1)可为null时执行的方法
private V putForNullKey(V value) {
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
if (e.key == null) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(0, null, value, 0);
return null;
}
//(2.2)hash值不一致时执行的方法
void addEntry(int hash, K key, V value, int bucketIndex) {
// (2.3)判断当前的hash链表是否需要扩容 如果超出阈值则进行扩容 扩容为两倍
if ((size >= threshold) && (null != table[bucketIndex])) {
(4.1)扩容
resize(2 * table.length);
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}
//(2.4)hash值不一致时执行的方法
createEntry(hash, key, value, bucketIndex);
}
//(2.5)新增Entry。将“key-value”插入指定位置,bucketIndex是位置索引
void createEntry(int hash, K key, V value, int bucketIndex) {//bucketIndex索引下标
Entry<K,V> e = table[bucketIndex];
//设置“e”为“新Entry的下一个节点” 当索引下标一致的时候新的键值对会在链表的第一个节点插入
table[bucketIndex] = new Entry<>(hash, key, value, e);
size++;
}
//获取索引下标 采用&的方式保证获取的下标小于等于length-1
//取于法的优化
static int indexFor(int h, int length) {
return h & (length-1);
}
//(3.1)提高对象hash码的质量,重写hash算法
final int hash(Object k) {
int h = hashSeed;
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
} h ^= k.hashCode(); // This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
//(4.1)HashMap初始化容器大小16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
public HashMap() {
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}
//(2.2)entry结构
static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
// 指向下一个节点
Entry<K,V> next;
final int hash; // 构造函数。
// 输入参数包括"哈希值(h)", "键(k)", "值(v)", "下一节点(n)"
Entry(int h, K k, V v, Entry<K,V> n) {
value = v;
next = n;
key = k;
hash = h;
} public final K getKey() {
return key;
}
} }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109

HashTable部分源码


public class HashTable{
//(1.2)插入时不允许key或者value为null (2)是线程安全的用synchronized做同步保证
public synchronized V put(K key, V value) {
// Make sure the value is not null 上来就报错
if (value == null) {
throw new NullPointerException();
} // Makes sure the key is not already in the hashtable.
Entry tab[] = table;
int hash = hash(key);//这里报错null调用hashcode方法的时候
(3)取模采用的是hash值去掉负号 再取模长度的方式
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
V old = e.value;
e.value = value;
return old;
}
} modCount++;
if (count >= threshold) {
// Rehash the table if the threshold is exceeded
//(4.1)扩容
rehash(); tab = table;
hash = hash(key);
index = (hash & 0x7FFFFFFF) % tab.length;
} // Creates the new entry.
Entry<K,V> e = tab[index];
tab[index] = new Entry<>(hash, key, value, e);
count++;
return null;
}
//(3.2)hash方法调用
private int hash(Object k) {
// hashSeed will be zero if alternative hashing is disabled.
return hashSeed ^ k.hashCode();
}
//(4.2)默认初始化容器大小
public Hashtable() {
this(11, 0.75f);
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49

2.是否线程安全性不同:HashMap是线程不安全的,HashTable是线程安全的,因为新增或者删除k,v的时候,比如说新增put方法(参见(2.1)和(2.2)entry结构至(2.5)) 会在链表的首个节点插入,如果有多线程进行操作 可能会造成后者覆盖前者的情况 所以线程不安全.而HashTable则是由synchronized方法做同步保证(所以也导致HashTable的速度较慢). 
3.Hash值计算方式不同:HashMap的获取索引下标及Hash()方法都不一致,hashmap有对对象的hash码就行优化,索引的获取用&计算替代取模计算.(可查看(3.1)和(3.2)) 
4.容器扩容方式不同:HashMap对象的初始化容器是16,而HashTable是11(可看(4)),二者的加载因子默认都是0.75,容器扩容 size(当前已经使用的容器槽位)>=threshold(阀值)=加载因子*initialCapacity(当前容大小)可查看(4.1)和(4.2)扩容; 个人观点 容器不可设置太小否则需要重新创建HashMap进行值的复制,加载因子默认0.75,设置过小也会需要经常再创建复制,这时候容器存储的数据还很稀疏.

最后看源码的过程中有参照了该作者的博客,如您要看源码请移驾HashMap源码博客 
地址:http://blog.csdn.net/ns_code/article/details/36034955

最新文章

  1. htmlentities,html_entity_decode,addslashes
  2. 关于如何在cenos7.0上实现mysql数据库远程连接
  3. C++ 无法将值写入注册表 HKEY_LOCAL_MACHINE\Sofeware\Microsoft\Windows\CurrentVersion\Run,以实现开机自启动应用程序。
  4. vmware workstation11+centos7+lnmp一键安装包 环境搭建
  5. [示例]NSEnumerator-使用枚举类型实现数组的逆序输出
  6. 使用CCUserDefault 推断用户是否是第一次登陆系统及UserDefault全路径的获取
  7. autocomplete+PHP+MYSQL的实现模糊查询
  8. Scrapy 爬虫实例教程(一)---简介及资源列表
  9. 中国大学MOOC-翁恺-C语言程序设计习题集-解答汇总
  10. this-&gt;的作用
  11. 使用 HttpClient 请求 Web Api
  12. js之Ajax下载文件
  13. 通过随机数获得学生成绩,并把每个元素赋值为学生的分数成绩,通过增强for循环遍历结果。
  14. IDEA创建Web项目(maven)
  15. python基础学习笔记(六)
  16. Last Defence (2014 西安现场赛)
  17. Disconf 学习系列之Disconf 与 Diamond的横向对比(图文详解)
  18. 巧用JS中的join方法操作字符串
  19. 在使用Hibernate save()方法的时候 报错: org.hibernate.exception.ConstraintViolationException:could not perform addBath
  20. iOS 截屏,openGL ES 截图,以及像素颜色判断

热门文章

  1. 智能dns或CDN应用中,如何很好的解决DNS缓存问题? - 知乎
  2. 通俗解释遗传算法及其Matlab实现
  3. 英雄pk理解面向对象中的this指针概念
  4. 启用多处理器编译--加快VS2013编译
  5. javascript模块化有什么意义?
  6. Android线程与线程池
  7. ylbtech-dbs-m-ele(饿了么)
  8. 1-N中1出现的次数
  9. wifi破解到局域网渗透
  10. driver: Linux设备模型之input子系统具体解释