Java数据结构-LinkedHashmap

来源:互联网 发布:邯郸学院软件学院 编辑:程序博客网 时间:2024/05/21 18:37

内部结构图

这里写图片描述

实现原理

其实如果不看图中的横向引用而只看竖向引用的话,LinkedHashMap和HashMap是差不多的,关于HashMap的结构可以查看http://blog.csdn.net/qq32933432/article/details/53013393
LinkedHashMap内部维护的Entry比HashMap中维护的Entry多了两个属性Entry<K,V> before, after;分别代表前一个引用和后一个引用。也就是说,LinkedHashMap中的entry每一个对象都持有他前后对象的引用。所以顺序是和插入的时候保持一致的。

特点

有序,顺序和插入时保持一致。
迭代的所需时间与数组本身大小无关,只与实际元素数量有关

常用方法源码

put(K key, V value)

public V put(K key, V value) {        if (table == EMPTY_TABLE) {            inflateTable(threshold);//如果是第一次吊用put方法则初始化数组,默认大小16        }        if (key == null)            return putForNullKey(value);        int hash = hash(key);        int i = indexFor(hash, table.length);//通过key决定key在hashmap中存放的位置        for (Entry<K,V> e = table[i]; e != null; e = e.next) {            Object k;            //如果key相同则替换原有的value            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;    }void addEntry(int hash, K key, V value, int bucketIndex) {        if ((size >= threshold) && (null != table[bucketIndex])) {            resize(2 * table.length);//进行数组扩容,扩容大小为原大小2倍            hash = (null != key) ? hash(key) : 0;            bucketIndex = indexFor(hash, table.length);        }        createEntry(hash, key, value, bucketIndex);//创建entry对象并放入数组中    }void createEntry(int hash, K key, V value, int bucketIndex) {        HashMap.Entry<K,V> old = table[bucketIndex];        Entry<K,V> e = new Entry<>(hash, key, value, old);        table[bucketIndex] = e;        e.addBefore(header);//修改引用        size++;    }private void addBefore(Entry<K,V> existingEntry) {            after  = existingEntry;            before = existingEntry.before;            before.after = this;            after.before = this;        }

get(Object key)

public V get(Object key) {        Entry<K,V> e = (Entry<K,V>)getEntry(key);        if (e == null)            return null;        e.recordAccess(this);        return e.value;    }final Entry<K,V> getEntry(Object key) {        if (size == 0) {            return null;        }        int hash = (key == null) ? 0 : hash(key);        for (Entry<K,V> e = table[indexFor(hash, table.length)];             e != null;             e = e.next) {            Object k;            //比较hash并获取值返回            if (e.hash == hash &&                ((k = e.key) == key || (key != null && key.equals(k))))                return e;        }        return null;    }
0 0
原创粉丝点击