java 1.7 hashmap源码_Java1.7的HashMap源码分析-面试必备技能

HashMap是现在用的最多的map,HashMap的源码可以说是面试必备技能,今天我们试着分析一下jdk1.7下的源码。

先说结论:数组加链表

d869701c14183c2e9c92db9eb3c870cc.png

一、先看整体的数据结构

首先我们注意到数据是存放在一个Entry数组里面,默认大小16.

public class HashMapextends AbstractMapimplements Map, Cloneable, Serializable

{

/**

* The default initial capacity - MUST be a power of two.

*/

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

/**

* The maximum capacity, used if a higher value is implicitly specified

* by either of the constructors with arguments.

* MUST be a power of two <= 1<<30.

*/

static final int MAXIMUM_CAPACITY = 1 << 30;

/**

* The load factor used when none specified in constructor.

*/

static final float DEFAULT_LOAD_FACTOR = 0.75f;

/**

* An empty table instance to share when the table is not inflated.

*/

static final Entry,?>[] EMPTY_TABLE = {};

/**

* The table, resized as necessary. Length MUST Always be a power of two.

*/

transient Entry[] table = (Entry[]) EMPTY_TABLE;

... ...

我们来看看Entry长什么样

static class Entryimplements Map.Entry{

final K key;

V value;

Entrynext;

int hash;

/**

* Creates new entry.

*/

Entry(int h, K k, V v, Entryn) {

value = v;

next = n;

key = k;

hash = h;

}

... ...

这是一个单链表结构,next指向下一个

二、put方法

我们来解析一下最常用的put方法

public V put(K key, V value) {

if (table == EMPTY_TABLE) {

inflateTable(threshold);

}

if (key == null)

return putForNullKey(value);

int hash = hash(key);

int i = indexFor(hash, table.length);

for (Entrye = 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++;

addEntry(hash, key, value, i);

return null;

}

我们一步步来分析,首先如果table为空就初始化table

if (table == EMPTY_TABLE) {

inflateTable(threshold);

}

我们来看看inflateTable(threshold)方法,就是计算初始化的大小,初始化table.

private void inflateTable(int toSize) {

// Find a power of 2 >= toSize

int capacity = roundUpToPowerOf2(toSize);

threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);

table = new Entry[capacity];

initHashSeedAsNeeded(capacity);

}

接着往下走,如果key是空的处理。

if (key == null)

return putForNullKey(value);

进到putForNullKey()方法我们知道它是把null放到了table[0],for循环里面是已经存在的数据进行替换;如果不存在,通过addEntry添加到table.

private V putForNullKey(V value) {

for (Entrye = 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;

}

回到put方法,往下走,获取hash,通过hash获取数组的下标i

int hash = hash(key);

int i = indexFor(hash, table.length);

接下来的for循环,是遍历下标i的链表,比较key和hash,替换相应的value

for (Entrye = 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;

}

}

for循环如果找到了,会把新值替换旧值,并返回oldvalue;

如果for循环没找到,则通过addEntry()添加到table

void addEntry(int hash, K key, V value, int bucketIndex) {

if ((size >= threshold) && (null != table[bucketIndex])) {

resize(2 * table.length);

hash = (null != key) ? hash(key) : 0;

bucketIndex = indexFor(hash, table.length);

}

createEntry(hash, key, value, bucketIndex);

}

先进行扩容,如果需要,然后添加,把新元素添加到第一位,之前的往后排

void createEntry(int hash, K key, V value, int bucketIndex) {

Entrye = table[bucketIndex];

table[bucketIndex] = new Entry<>(hash, key, value, e);

size++;

}

总结一下:

先用key生成hash,定位到数组的下标

如果遍历链表,查找,找到之后替换,返回

如果没找到,把数据插入到第一位

三、get方法

get方法就简单了

public V get(Object key) {

if (key == null)

return getForNullKey();

Entryentry = getEntry(key);

return null == entry ? null : entry.getValue();

}

如果key为null,从第一位table[0]找

private V getForNullKey() {

if (size == 0) {

return null;

}

for (Entrye = table[0]; e != null; e = e.next) {

if (e.key == null)

return e.value;

}

return null;

}

如果key不是null,走getEntry,基本就和put的逻辑反过来就行了

final EntrygetEntry(Object key) {

if (size == 0) {

return null;

}

int hash = (key == null) ? 0 : hash(key);

for (Entrye = table[indexFor(hash, table.length)];

e != null;

e = e.next) {

Object k;

if (e.hash == hash &&

((k = e.key) == key || (key != null && key.equals(k))))

return e;

}

return null;

}

通过key,计算hash,在计算数组的下标i, 从链表的第一位开始,比较key和hash,一直往后遍历,直到找到值,返回e;

最后,如果没找到,返回null.

四、思考

我们想一想,这个结构还有什么问题吗?

如果hash算法不好,好多key都落在同一个下标,那么链表是不是超长?

我们改天说说java1.8是怎么改进这个问题的。

文章来源: www.cnblogs.com,作者:丰极,版权归原作者所有,如需转载,请联系作者。

原文链接:https://www.cnblogs.com/zhangbin1989/p/13230015.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值