---
title: "Hashmap实现原理(转)"
author: "JyeChou"
date: "2014-09-24T10:25:13Z"
tags: []
categories: ["编程语言"]
slug: "hashmap"
draft: false
lastmod: "2018-08-20T10:24:27Z"
id: 2119876
url: "https://jyechou.iteye.com/blog/2119876"
---

## 参考文献：

[hash算法 (hashmap 实现原理)](http://zha-zi.iteye.com/blog/1124484)

[Java实现的散列表](http://www.cxybl.com/html/suanfa/201110125445.html)

## 1.HashMap的数据结构

　　**数组**的特点是：寻址容易，插入和删除困难；而**链表**的特点是：寻址困难，插入和删除容易。那么我们能不能综合两者的特性，做出一种寻址容易，插入删除也容易的数据结构？答案是肯定的，这就是我们要提起的**哈希表**，哈希表有多种不同的实现方法，我接下来解释的是最常用的一种方法—— 拉链法，我们可以理解为“**链表的数组**” ，如图：

![](http://pic002.cnblogs.com/images/2012/80896/2012051414243547.png)

　　从上图我们可以发现哈希表是由数组+链表组成的，一个长度为16的数组中，每个元素存储的是一个链表的头结点。那么这些元素是按照什么样的规则 存储到数组中呢。一般情况是通过hash(key)%len获得，也就是元素的key的哈希值对数组长度取模得到。比如上述哈希表 中，12%16=12,28%16=12,108%16=12,140%16=12。所以12、28、108以及140都存储在数组下标为12的位置。

　　HashMap其实也是一个线性的数组实现的,所以可以理解为其存储数据的容器就是一个线性数组。这可能让我们很不解，一个线性的数组怎么实现按键值对来存取数据呢？这里HashMap有做一些处理。

　　1.首先HashMap里面实现一个静态内部类Entry，其重要的属性有 key , value, next，从属性key,value我们就能很明显的看出来Entry就是HashMap键值对实现的一个基础bean，我们上面说到HashMap的基 础就是一个线性数组，这个数组就是Entry\[]，Map里面的内容都保存在Entry\[]里面。

## 2.HashMap的存取实现

     既然是线性数组，为什么能随机存取？这里HashMap用了一个小算法，大致是这样实现：

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

```
//存储时:
int hash = key.hashCode();// 这个hashCode方法这里不详述,只要理解每个key的hash是一个固定的int值
int index = hash % Entry[].length;
Entry[index] = value;

//取值时:
int hash = key.hashCode();
int index = hash % Entry[].length;
return Entry[index];
```

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

到这里我们轻松的理解了HashMap通过键值对实现存取的基本原理

    3.疑问：如果两个key通过hash%Entry\[].length得到的index相同，会不会有覆盖的危险？

　　这里HashMap里面用到链式数据结构的一个概念。上面我们提到过Entry类里面有一个next属性，作用是指向下一个Entry。打个比 方， 第一个键值对A进来，通过计算其key的hash得到的index=0，记做:Entry\[0] = A。一会后又进来一个键值对B，通过计算其index也等于0，现在怎么办？HashMap会这样做:B.next = A,Entry\[0] = B,如果又进来C,index也等于0,那么C.next = B,Entry\[0] = C；这样我们发现index=0的地方其实存取了A,B,C三个键值对,他们通过next这个属性链接在一起。所以疑问不用担心。**也就是说数组中存储的是最后插入的元素。**到这里为止，HashMap的大致实现，我们应该已经清楚了。

　　当然HashMap里面也包含一些优化方面的实现，这里也说一下。比如：Entry\[]的长度一定后，随着map里面数据的越来越长，这样同一 个index的链就会很长，会不会影响性能？HashMap里面设置一个因素（也称为因子），随着map的size越来越大，Entry\[]会以一定的规 则加长长度。

## 3.解决hash冲突的办法

1. 开放定址法（线性探测再散列，二次探测再散列，伪随机探测再散列）
2. 再哈希法
3. 链地址法
4. 建立一个公共溢出区

Java中hashmap的解决办法就是采用的链地址法。

## 4.实现自己的HashMap

 

### Entry.java

![](http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

```
package edu.sjtu.erplab.hash;

public class Entry<K,V>{
    final K key;
    V value;
    Entry<K,V> next;//下一个结点
 
    //构造函数
    public Entry(K k, V v, Entry<K,V> n) {
        key = k;
        value = v;
        next = n;
    }

    public final K getKey() {
        return key;
    }

    public final V getValue() {
        return value;
    }

    public final V setValue(V newValue) {
    V oldValue = value;
        value = newValue;
        return oldValue;
    }

    public final boolean equals(Object o) {
        if (!(o instanceof Entry))
            return false;
        Entry e = (Entry)o;
        Object k1 = getKey();
        Object k2 = e.getKey();
        if (k1 == k2 || (k1 != null && k1.equals(k2))) {
            Object v1 = getValue();
            Object v2 = e.getValue();
            if (v1 == v2 || (v1 != null && v1.equals(v2)))
                return true;
        }
        return false;
    }

    public final int hashCode() {
        return (key==null   ? 0 : key.hashCode()) ^ (value==null ? 0 : value.hashCode());
    }

    public final String toString() {
        return getKey() + "=" + getValue();
    }

}
```

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

### MyHashMap.java

![](http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

```
package edu.sjtu.erplab.hash;

//保证key与value不为空
public class MyHashMap<K, V> {
    private Entry[] table;//Entry数组表
    static final int DEFAULT_INITIAL_CAPACITY = 16;//默认数组长度
    private int size;

    // 构造函数
    public MyHashMap() {
        table = new Entry[DEFAULT_INITIAL_CAPACITY];
        size = DEFAULT_INITIAL_CAPACITY;
    }

    //获取数组长度
    public int getSize() {
        return size;
    }
    
    // 求index
    static int indexFor(int h, int length) {
        return h % (length - 1);
    }

    //获取元素
    public V get(Object key) {
        if (key == null)
            return null;
        int hash = key.hashCode();// key的哈希值
        int index = indexFor(hash, table.length);// 求key在数组中的下标
        for (Entry<K, V> e = table[index]; e != null; e = e.next) {
            Object k = e.key;
            if (e.key.hashCode() == hash && (k == key || key.equals(k)))
                return e.value;
        }
        return null;
    }

    // 添加元素
    public V put(K key, V value) {
        if (key == null)
            return null;
        int hash = key.hashCode();
        int index = indexFor(hash, table.length);

        // 如果添加的key已经存在，那么只需要修改value值即可
        for (Entry<K, V> e = table[index]; e != null; e = e.next) {
            Object k = e.key;
            if (e.key.hashCode() == hash && (k == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                return oldValue;// 原来的value值
            }
        }
        // 如果key值不存在，那么需要添加
        Entry<K, V> e = table[index];// 获取当前数组中的e
        table[index] = new Entry<K, V>(key, value, e);// 新建一个Entry，并将其指向原先的e
        return null;
    }

}
```

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

### MyHashMapTest.java

![](http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

```
package edu.sjtu.erplab.hash;

public class MyHashMapTest {

    public static void main(String[] args) {

        MyHashMap<Integer, Integer> map = new MyHashMap<Integer, Integer>();
        map.put(1, 90);
        map.put(2, 95);
        map.put(17, 85);
    
        System.out.println(map.get(1));
        System.out.println(map.get(2));
        System.out.println(map.get(17));
        System.out.println(map.get(null));
    }
}
```