HashMap put()方法返回值解析

Map 存储k-v 对时的返回值:

 public static void main(String[] args) {
        Map m= new HashMap();
        String s1= m.put("001","zhangsan");
        String s2=m.put("001","wangwu");
        sop(s1);
        sop(s2);
    }

    public static void sop(Object obj)
    {
        System.out.println(obj);
    }

结果:

null

zhangsan

 

分析:

因为返回值是与key 关联的旧值,因此第一次时,因为没有与key关联的旧值,所以会返回null, 而第二次与key 关联的旧值是“zhangsan”,所以返回值是“张三”

 

源码分析:

HashMap

public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
    
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node[] tab; Node p; int n, i;
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node e; K k;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        else if (p instanceof TreeNode)
            e = ((TreeNode)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;
                }
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                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;
    }

注意:①处,如果要放入map中的key已经存在了,就把已经存在的key的值返回

 

你可能感兴趣的:(java,基础知识)