集合-Map

目录

HashMap

默认值

插入元素 

获取元素 


Map继承关系如下图所示:

Map接口方法如下所示。 

HashMap

HashMap是我们经常使用的类,现在我们来看看 HashMap 是如何实现的。

默认值

默认值,这个面试的时候经常问到

//初始化默认容量大小为16,必须为2的n次方;
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;

//最大容量大小为2的30次方
static final int MAXIMUM_CAPACITY = 1 << 30;

//默认加载因子为0.75f
static final float DEFAULT_LOAD_FACTOR = 0.75f;

//由链表转换成树的阈值
static final int TREEIFY_THRESHOLD = 8;

//由树转换成链表的阈值
static final int UNTREEIFY_THRESHOLD = 6;

//转化为红黑树大最小table大小
static final int MIN_TREEIFY_CAPACITY = 64;

插入元素 

V put(K key, V value) ,第一个参数为key,第二个参数为对于的value值

public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
}

int hash(Object key)  ,当key为空时,则hash值为0

static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict)
参数说明:

hash: hash(key)计算后的值,其中key = null时候 hash(null)=0
key: key值
value: value值
onlyIfAbsent: 为true,如果key存在,不修改value值。
evict:

返回值:  为旧的value值

  /**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //如果table为空时,调用扩容方法
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //不存在,创建一个新的节点赋值给tab[i]
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))  //key存在,
                e = p;
            else if (p instanceof TreeNode) //树节点
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        //将创建的节点添加到尾部
                        p.next = newNode(hash, key, value, null);
                        //转化为红黑树
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //若key存在,退出循环
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    //p引用指向p.next
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        //超过阈值,扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
final void treeifyBin(Node<K,V>[] tab, int hash) 

如果tab的长度小于MIN_TREEIFY_CAPACITY也就是64,则调用resize()方法扩容。否则,将链表转成红黑树。

/**
     * Replaces all linked nodes in bin at index for given hash unless
     * table is too small, in which case resizes instead.
     */
    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        //若tab的长度小于64,则进行扩容
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            TreeNode<K,V> hd = null, tl = null;
            //Node转成TreeNode,然后重新构建以TreeNode节点的链表
            do {
                //Node转成TreeNode
                TreeNode<K,V> p = replacementTreeNode(e, null);
                if (tl == null)
                    hd = p;
                else {
                    p.prev = tl;
                    tl.next = p;
                }
                tl = p;
            } while ((e = e.next) != null);
            
            if ((tab[index] = hd) != null)
                hd.treeify(tab); //将双向链表转化为红黑树
        }
    }

获取元素 

V get(Object key) 根据key获取value值

    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
     final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            //首先对比桶里的第一个节点,判断key的hash ,和key是否相等
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                //若为红黑树
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                //若为链表,并且不是桶里的第一个节点,循环判断key的hash ,和key是否相等
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        //不存在,返回为null
        return null;
    }

遍历元素

在调用put()方法添加元素时,并没有将元素插入到entrySet属性中。entrySet属性其实不存放任何值,entrySet() 遍历其实是调用EntryIterator.next()方法 。

public Set<Map.Entry<K,V>> entrySet() {
        Set<Map.Entry<K,V>> es;
        return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}

遍历时实际上调用HashIterator的next()方法。 

final class EntryIterator extends HashIterator
        implements Iterator<Map.Entry<K,V>> {
     public final Map.Entry<K,V> next() { return nextNode(); }
}

//
abstract class HashIterator {
        Node<K,V> next;        // next entry to return
        Node<K,V> current;     // current entry
        int expectedModCount;  // for fast-fail
        int index;             // current slot

        HashIterator() {
            expectedModCount = modCount;
            Node<K,V>[] t = table;
            current = next = null;
            index = 0;
            if (t != null && size > 0) { // advance to first entry
                do {} while (index < t.length && (next = t[index++]) == null);
            }
        }

        public final boolean hasNext() {
            return next != null;
        }

        final Node<K,V> nextNode() {
            Node<K,V>[] t;
            Node<K,V> e = next;
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            if (e == null)
                throw new NoSuchElementException();
            if ((next = (current = e).next) == null && (t = table) != null) {
                do {} while (index < t.length && (next = t[index++]) == null);
            }
            return e;
        }

        public final void remove() {
            Node<K,V> p = current;
            if (p == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            current = null;
            K key = p.key;
            removeNode(hash(key), key, null, false, false);
            expectedModCount = modCount;
        }
    }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值