HashMap、HashTable、HashSet的实现原理和底层数据结构

Love The Way You Lie 2022-05-26 08:21 303阅读 0赞

原文:http://blog.51cto.com/10414498/1846953

HashMap和Hashtable的区别

  1. 两者最主要的区别在于Hashtable是线程安全,而HashMap则非线程安全
    Hashtable的实现方法里面都添加了synchronized关键字来确保线程同步,因此相对而言HashMap性能会高一些,我们平时使用时若无特殊需求建议使用HashMap,在多线程环境下若使用HashMap需要使用Collections.synchronizedMap()方法来获取一个线程安全的集合(Collections.synchronizedMap()实现原理是Collections定义了一个SynchronizedMap的内部类,这个类实现了Map接口,在调用方法时使用synchronized来保证线程同步,当然了实际上操作的还是我们传入的HashMap实例,简单的说就是Collections.synchronizedMap()方法帮我们在操作HashMap时自动添加了synchronized来实现线程同步,类似的其它Collections.synchronizedXX方法也是类似原理)
  2. HashMap可以使用null作为key,而Hashtable则不允许null作为key
    虽说HashMap支持null值作为key,不过建议还是尽量避免这样使用,因为一旦不小心使用了,若因此引发一些问题,排查起来很是费事
    HashMap以null作为key时,总是存储在table数组的第一个节点上
  3. HashMap是对Map接口的实现,HashTable实现了Map接口和Dictionary抽象类
  4. HashMap的初始容量为16,Hashtable初始容量为11,两者的填充因子默认都是0.75
    HashMap扩容时是当前容量翻倍即:capacity*2,Hashtable扩容时是容量翻倍+1即:capacity*2+1
  5. 两者计算hash的方法不同
    Hashtable计算hash是直接使用key的hashcode对table数组的长度直接进行取模
  1. int hash = key.hashCode();int index = (hash & 0x7FFFFFFF) % tab.length;
  2. HashMap计算hashkeyhashcode进行了二次hash,以获得更好的散列值,然后对table数组长度取摸
  3. static int hash(int h) { // This function ensures that hashCodes that differ only by
  4. // constant multiples at each bit position have a bounded
  5. // number of collisions (approximately 8 at default load factor).
  6. h ^= (h >>> 20) ^ (h >>> 12); return h ^ (h >>> 7) ^ (h >>> 4);
  7. } static int indexFor(int h, int length) { return h & (length-1);
  8. }
  1. HashMap和Hashtable的底层实现都是数组+链表结构实现

HashSet和HashMap、Hashtable的区别

除开HashMap和Hashtable外,还有一个hash集合HashSet,有所区别的是HashSet不是key value结构,仅仅是存储不重复的元素,相当于简化版的HashMap,只是包含HashMap中的key而已

通过查看源码也证实了这一点,HashSet内部就是使用HashMap实现,只不过HashSet里面的HashMap所有的value都是同一个Object而已,因此HashSet也是非线程安全的,至于HashSet和Hashtable的区别,HashSet就是个简化的HashMap的,所以你懂的
下面是HashSet几个主要方法的实现

  1. HashMap<E,Object>= HashMap<E,Object> map.put(e, PRESENT)== map.put(e, PRESENT)== map.remove(o)==

HashMap和Hashtable的实现原理

HashMap和Hashtable的底层实现都是数组+链表结构实现的,这点上完全一致

添加、删除、获取元素时都是先计算hash,根据hash和table.length计算index也就是table数组的下标,然后进行相应操作,下面以HashMap为例说明下它的简单实现

  1. /**
  2. * HashMap的默认初始容量 必须为2的n次幂 */
  3. static final int DEFAULT_INITIAL_CAPACITY = 16; /**
  4. * HashMap的最大容量,可以认为是int的最大值
  5. */
  6. static final int MAXIMUM_CAPACITY = 1 << 30; /**
  7. * 默认的加载因子 */
  8. static final float DEFAULT_LOAD_FACTOR = 0.75f; /**
  9. * HashMap用来存储数据的数组 */
  10. transient Entry[] table;
  • HashMap的创建
    HashMap默认初始化时会创建一个默认容量为16的Entry数组,默认加载因子为0.75,同时设置临界值为16*0.75
  1. /**
  2. * Constructs an empty <tt>HashMap</tt> with the default initial capacity
  3. * (16) and the default load factor (0.75). */
  4. public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR;
  5. threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
  6. table = new Entry[DEFAULT_INITIAL_CAPACITY];
  7. init();
  8. }
  • put方法
    HashMap会对null值key进行特殊处理,总是放到table[0]位置
    put过程是先计算hash然后通过hash与table.length取摸计算index值,然后将key放到table[index]位置,当table[index]已存在其它元素时,会在table[index]位置形成一个链表,将新添加的元素放在table[index],原来的元素通过Entry的next进行链接,这样以链表形式解决hash冲突问题,当元素数量达到临界值(capactiy*factor)时,则进行扩容,是table数组长度变为table.length*2
  • public V put(K key, V value) { if (key == null) return putForNullKey(value); //处理null值
    int hash = hash(key.hashCode());//计算hash
    int i = indexFor(hash, table.length);//计算在数组中的存储位置
    //遍历table[i]位置的链表,查找相同的key,若找到则使用新的value替换掉原来的oldValue并返回oldValue
    for (Entry e = table[i]; e != null; e = e.next) {
    1. Object k; if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
    2. V oldValue = e.value;
    3. e.value = value;
    4. e.recordAccess(this); return oldValue;
    5. }
    } //若没有在table[i]位置找到相同的key,则添加key到table[i]位置,新的元素总是在table[i]位置的第一个元素,原来的元素后移
    modCount++;
    addEntry(hash, key, value, i); return null;
    }
    void addEntry(int hash, K key, V value, int bucketIndex) { //添加key到table[bucketIndex]位置,新的元素总是在table[bucketIndex]的第一个元素,原来的元素后移
    Entry e = table[bucketIndex];
    table[bucketIndex] = new Entry(hash, key, value, e); //判断元素个数是否达到了临界值,若已达到临界值则扩容,table长度翻倍
    if (size++ >= threshold)
    1. resize(2 * table.length);
    }
  • get方法
    同样当key为null时会进行特殊处理,在table[0]的链表上查找key为null的元素
    get的过程是先计算hash然后通过hash与table.length取摸计算index值,然后遍历table[index]上的链表,直到找到key,然后返回
  1. public V get(Object key) { if (key == null) return getForNullKey();//处理null值
  2. int hash = hash(key.hashCode());//计算hash
  3. //在table[index]遍历查找key,若找到则返回value,找不到返回null
  4. for (Entry<K,V> e = table[indexFor(hash, table.length)];
  5. e != null;
  6. e = e.next) {
  7. Object k; if (e.hash == hash && ((k = e.key) == key || key.equals(k))) return e.value;
  8. } return null;
  9. }
  • remove方法
    remove方法和put get类似,计算hash,计算index,然后遍历查找,将找到的元素从table[index]链表移除
  1. public V remove(Object key) {
  2. Entry<K,V> e = removeEntryForKey(key); return (e == null ? null : e.value);
  3. } final Entry<K,V> removeEntryForKey(Object key) { int hash = (key == null) ? 0 : hash(key.hashCode()); int i = indexFor(hash, table.length);
  4. Entry<K,V> prev = table[i];
  5. Entry<K,V> e = prev; while (e != null) {
  6. Entry<K,V> next = e.next;
  7. Object k; if (e.hash == hash &&
  8. ((k = e.key) == key || (key != null && key.equals(k)))) {
  9. modCount++;
  10. size--; if (prev == e)
  11. table[i] = next; else
  12. prev.next = next;
  13. e.recordRemoval(this); return e;
  14. }
  15. prev = e;
  16. e = next;
  17. } return e;
  18. }
  • resize方法
    resize方法在hashmap中并没有公开,这个方法实现了非常重要的hashmap扩容,具体过程为:先创建一个容量为table.length*2的新table,修改临界值,然后把table里面元素计算hash值并使用hash与table.length*2重新计算index放入到新的table里面
    这里需要注意下是用每个元素的hash全部重新计算index,而不是简单的把原table对应index位置元素简单的移动到新table对应位置
  1. resize(= oldCapacity = (oldCapacity ==== == ()(newCapacity *= newCapacity = ( j = ; j < src.; j++<K,V> e = (e != = <K,V> = i ==== (e !=
  • clear()方法
    clear方法非常简单,就是遍历table然后把每个位置置为null,同时修改元素个数为0
    需要注意的是clear方法只会清楚里面的元素,并不会重置capactiy
  1. public void clear() {
  2. modCount++;
  3. Entry[] tab = table; for (int i = 0; i < tab.length; i++)
  4. tab[i] = null;
  5. size = 0;
  6. }
  • containsKey和containsValue
    containsKey方法是先计算hash然后使用hash和table.length取摸得到index值,遍历table[index]元素查找是否包含key相同的值
  1. public boolean containsKey(Object key) { return getEntry(key) != null;
  2. }final Entry<K,V> getEntry(Object key) { int hash = (key == null) ? 0 : hash(key.hashCode()); for (Entry<K,V> e = table[indexFor(hash, table.length)];
  3. e != null;
  4. e = e.next) {
  5. Object k; if (e.hash == hash &&
  6. ((k = e.key) == key || (key != null && key.equals(k)))) return e;
  7. } return null;
  8. }
  9. containsValue方法就比较粗暴了,就是直接遍历所有元素直到找到value,由此可见HashMapcontainsValue方法本质上和普通数组和listcontains方法没什么区别,你别指望它会像containsKey那么高效
  10. public boolean containsValue(Object value) { if (value == null) return containsNullValue();
  11. Entry[] tab = table; for (int i = 0; i < tab.length ; i++) for (Entry e = tab[i] ; e != null ; e = e.next) if (value.equals(e.value)) return true; return false;
  12. }
  • hash和indexFor
  1. indexFor中的h & (-)就相当于h,用于计算也就是在table数组中的下标
  2. hash方法是对hashcode进行二次散列,以获得更好的散列值
  3. 为了更好理解这里我们可以把这两个方法简化为 = key.hashCode()/table.,以put中的方法为例可以这样替换
  4. int hash = hash(key.hashCode());//计算hashint i = indexFor(hash, table.length);//计算在数组中的存储位置//上面这两行可以这样简化int i = key.key.hashCode()%table.length;
  • static int hash(int h) { // This function ensures that hashCodes that differ only by
    1. // constant multiples at each bit position have a bounded
    2. // number of collisions (approximately 8 at default load factor).
    3. h ^= (h >>> 20) ^ (h >>> 12); return h ^ (h >>> 7) ^ (h >>> 4);
    } static int indexFor(int h, int length) { return h & (length-1);
    }

HashMap的简化实现MyHashMap

为了加深理解,我个人实现了一个简化版本的HashMap,注意哦,仅仅是简化版的功能并不完善,仅供参考

169_598_df8.gif

  1. package cn.lzrabbit.structure;/**
  2. * Created by rabbit on 14-5-4. */public class MyHashMap { //默认初始化大小 16
  3. private static final int DEFAULT_INITIAL_CAPACITY = 16; //默认负载因子 0.75
  4. private static final float DEFAULT_LOAD_FACTOR = 0.75f; //临界值
  5. private int threshold; //元素个数
  6. private int size; //扩容次数
  7. private int resize; private HashEntry[] table; public MyHashMap() {
  8. table = new HashEntry[DEFAULT_INITIAL_CAPACITY];
  9. threshold = (int) (DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
  10. size = 0;
  11. } private int index(Object key) { //根据key的hashcode和table长度取模计算key在table中的位置
  12. return key.hashCode() % table.length;
  13. } public void put(Object key, Object value) { //key为null时需要特殊处理,为简化实现忽略null值
  14. if (key == null) return; int index = index(key); //遍历index位置的entry,若找到重复key则更新对应entry的值,然后返回
  15. HashEntry entry = table[index]; while (entry != null) { if (entry.getKey().hashCode() == key.hashCode() && (entry.getKey() == key || entry.getKey().equals(key))) {
  16. entry.setValue(value); return;
  17. }
  18. entry = entry.getNext();
  19. } //若index位置没有entry或者未找到重复的key,则将新key添加到table的index位置 add(index, key, value);
  20. } private void add(int index, Object key, Object value) { //将新的entry放到table的index位置第一个,若原来有值则以链表形式存放
  21. HashEntry entry = new HashEntry(key, value, table[index]);
  22. table[index] = entry; //判断size是否达到临界值,若已达到则进行扩容,将table的capacicy翻倍
  23. if (size++ >= threshold) {
  24. resize(table.length * 2);
  25. }
  26. } private void resize(int capacity) { if (capacity <= table.length) return;
  27. HashEntry[] newTable = new HashEntry[capacity]; //遍历原table,将每个entry都重新计算hash放入newTable中
  28. for (int i = 0; i < table.length; i++) {
  29. HashEntry old = table[i]; while (old != null) {
  30. HashEntry next = old.getNext(); int index = index(old.getKey());
  31. old.setNext(newTable[index]);
  32. newTable[index] = old;
  33. old = next;
  34. }
  35. } //用newTable替table
  36. table = newTable; //修改临界值
  37. threshold = (int) (table.length * DEFAULT_LOAD_FACTOR);
  38. resize++;
  39. } public Object get(Object key) { //这里简化处理,忽略null值
  40. if (key == null) return null;
  41. HashEntry entry = getEntry(key); return entry == null ? null : entry.getValue();
  42. } public HashEntry getEntry(Object key) {
  43. HashEntry entry = table[index(key)]; while (entry != null) { if (entry.getKey().hashCode() == key.hashCode() && (entry.getKey() == key || entry.getKey().equals(key))) { return entry;
  44. }
  45. entry = entry.getNext();
  46. } return null;
  47. } public void remove(Object key) { if (key == null) return; int index = index(key);
  48. HashEntry pre = null;
  49. HashEntry entry = table[index]; while (entry != null) { if (entry.getKey().hashCode() == key.hashCode() && (entry.getKey() == key || entry.getKey().equals(key))) { if (pre == null) table[index] = entry.getNext(); else pre.setNext(entry.getNext()); //如果成功找到并删除,修改size
  50. size--; return;
  51. }
  52. pre = entry;
  53. entry = entry.getNext();
  54. }
  55. } public boolean containsKey(Object key) { if (key == null) return false; return getEntry(key) != null;
  56. } public int size() { return this.size;
  57. } public void clear() { for (int i = 0; i < table.length; i++) {
  58. table[i] = null;
  59. } this.size = 0;
  60. }
  61. @Override public String toString() {
  62. StringBuilder sb = new StringBuilder();
  63. sb.append(String.format("size:%s capacity:%s resize:%s\n\n", size, table.length, resize)); for (HashEntry entry : table) { while (entry != null) {
  64. sb.append(entry.getKey() + ":" + entry.getValue() + "\n");
  65. entry = entry.getNext();
  66. }
  67. } return sb.toString();
  68. }
  69. }class HashEntry { private final Object key; private Object value; private HashEntry next; public HashEntry(Object key, Object value, HashEntry next) { this.key = key; this.value = value; this.next = next;
  70. } public Object getKey() { return key;
  71. } public Object getValue() { return value;
  72. } public void setValue(Object value) { this.value = value;
  73. } public HashEntry getNext() { return next;
  74. } public void setNext(HashEntry next) { this.next = next;
  75. }
  76. }

发表评论

表情:
评论列表 (有 0 条评论,303人围观)

还没有评论,来说两句吧...

相关阅读