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

HashMap与HashTable原理及数据结构的更多相关文章

  1. HashMap的工作原理--重点----数据结构示意图的理解

    转载:http://blog.csdn.net/qq_27093465/article/details/52209814 HashMap的工作原理是近年来常见的Java面试题.几乎每个Java程序员都 ...

  2. HashMap,Hashtable,ConcurrentHashMap 和 synchronized Map 的原理和区别

    HashMap 是否是线程安全的,如何在线程安全的前提下使用 HashMap,其实也就是HashMap,Hashtable,ConcurrentHashMap 和 synchronized Map 的 ...

  3. HashMap,HashTable,ConcurrentHashMap的实现原理及区别

    http://youzhixueyuan.com/concurrenthashmap.html 一.哈希表 哈希表就是一种以 键-值(key-indexed) 存储数据的结构,我们只要输入待查找的值即 ...

  4. HashMap底层实现原理/HashMap与HashTable区别/HashMap与HashSet区别

    ①HashMap的工作原理 HashMap基于hashing原理,我们通过put()和get()方法储存和获取对象.当我们将键值对传递给put()方法时,它调用键对象的hashCode()方法来计算h ...

  5. (转)HashMap底层实现原理/HashMap与HashTable区别/HashMap与HashSet区别

    ①HashMap的工作原理 HashMap基于hashing原理,我们通过put()和get()方法储存和获取对象.当我们将键值对传递给put()方法时,它调用键对象的hashCode()方法来计算h ...

  6. HashMap底层实现原理以及HashMap与HashTable区别以及HashMap与HashSet区别

    ①HashMap的工作原理 HashMap基于hashing原理,我们通过put()和get()方法储存和获取对象.当我们将键值对传递给put()方法时,它调用键对象的hashCode()方法来计算h ...

  7. HashMap底层实现原理/HashMap与HashTable区别/HashMap与HashSet区别(转)

    HashMap底层实现原理/HashMap与HashTable区别/HashMap与HashSet区别 文章来源:http://www.cnblogs.com/beatIteWeNerverGiveU ...

  8. Hashmap与Hashtable的区别及Hashmap的原理

    Hashtable和HashMap有几个主要的不同:线程安全以及速度.仅在你需要完全的线程安全的时候使用Hashtable,而如果你使用Java 5或以上的话,请使用ConcurrentHashMap ...

  9. HashMap的实现原理和底层数据结构

    看了下Java里面有HashMap.Hashtable.HashSet三种hash集合的实现源码,这里总结下,理解错误的地方还望指正 HashMap和Hashtable的区别 HashSet和Hash ...

随机推荐

  1. EF需要注意的virtual,懒加载,还有1对n更新

    1.如果实体类型有任何一个集合属性是 virtual 的,那么该属性会懒加载,在查询该对象时,看到的类型是代理对象(proxy_xxxx), 使用new来更新1对n关系时会 增加 ).FirstOrD ...

  2. hdu2829 四边形优化dp

    Lawrence Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total S ...

  3. Node.js 调用 restful webservice

    如何构建一个restful web service参考原来的文章 http://www.cnblogs.com/ericnie/p/5212748.html 直接用原来的项目编译好像有问题,此处耗费1 ...

  4. Memcached网络模型

    之前用libevent开发了一个流媒体服务器.用线程池实现的.之后又看了memcached的网络相关实现,今天来整理一下memcached的实现流程. memcached不同于Redis的单进程单线程 ...

  5. Less 简介

    什么是LESSCSS LESSCSS是一种动态样式语言,属于CSS预处理语言的一种,它使用类似CSS的语法,为CSS的赋予了动态语言的特性,如变量.继承.运算.函数等,更方便CSS的编写和维护. LE ...

  6. 集合—ArrayList

    ArrayList也叫作数组列表 public static void main(String[] args) { List list1 = new ArrayList<String>() ...

  7. 【业务自动化】iTop,全面支持ITIL流程的一款ITSM工具

    iTop产品针对的主要应用场景为:内部IT支持.IT外包管理.数据中心运维管理和企业IT资产管理.常青管理从绿象认证产品中选取了iTop作为主要推荐产品,本类别的绿象认证产品还包括:OTRS和RT3等 ...

  8. Android 之UI自适应解决方式

    1.概况 作为Android开发者,最头疼的莫过于让自己开发的程序在不同终端上面的显示效果看起来尽量一致(当然.假设要充分利用大屏幕的优势另当别论).在全球范围内来讲.android有着数以亿计的设备 ...

  9. 利用pandas进行数据分析之三:DataFrame与Series基本功能

    未经同意请勿转载http://www.cnblogs.com/smallcrystal/ 前文已经详细介绍DataFrame与Series两种数据结构,下面介绍DataFrame与Series的数据基 ...

  10. 在Eclipse中导入dtd和xsd文件,使XML自动提示(转)

    DTD 类型约束文件 1. Window->Preferences->XML->XML Catalog->User Specified Entries窗口中,选择Add 按纽 ...