hashmap

//继承自AbstractMap<K,V>,实现了Map接口,Cloneable,Seralizable接口。
public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable 
//初始化默认容量,16,全部使用位运算,故每次扩容一定是两倍
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
//初始化最大容量,自动扩容必须在这个范围内
 static final int MAXIMUM_CAPACITY = 1 << 30;
//扩容因子,每次存放的桶超过当前容量和扩容因子的乘积,则扩容第一次扩容是大于16*0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//桶内节点的个数超过8时会将其转化为红黑树
    static final int TREEIFY_THRESHOLD = 8;
//桶内节点的个数小于6时会将其转化为普通链表
static final int UNTREEIFY_THRESHOLD = 6;
//转换树型的最小容量,只有超过此值才允许表中桶转化成红黑树
static final int MIN_TREEIFY_CAPACITY = 64;
//静态内部类,将Node数组作为其数据结构,并实现了map内的Entry接口
static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;
        //每个节点的构造函数
        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }
        
        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }
        //返回当前Node的hashCode,(^异或运算)如果返回1,则表示key==null或者value==null
        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }
        //修改当前节点的value值
        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }
        //判断传入的对象的key和Value是否和当前对象相等
        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }
//计算key的hash值,将高16位参与运算,避免了碰撞
static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

至于如何避免的请参考:https://blog.csdn.net/fan2012huan/article/details/51097331

//不理解 
static Class<?> comparableClassFor(Object x) {
        if (x instanceof Comparable) {
            Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
            if ((c = x.getClass()) == String.class) // bypass checks
                return c;
            if ((ts = c.getGenericInterfaces()) != null) {
                for (int i = 0; i < ts.length; ++i) {
                    if (((t = ts[i]) instanceof ParameterizedType) &&
                        ((p = (ParameterizedType)t).getRawType() ==
                         Comparable.class) &&
                        (as = p.getActualTypeArguments()) != null &&
                        as.length == 1 && as[0] == c) // type arg is c
                        return c;
                }
            }
        }
        return null;
    }

 

//不理解
static int compareComparables(Class<?> kc, Object k, Object x) {
        return (x == null || x.getClass() != kc ? 0 :
                ((Comparable)k).compareTo(x));
    }
//扩容函数,获得当前n的位数,如果0<n<=30,则将容量扩大一倍
static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }
//存放KV的数据结构,
transient Node<K,V>[] table;
//用于遍历keys和values的数据结构
transient Set<Map.Entry<K,V>> entrySet;
//map中存放KV的个数
transient int size;
//记录被修改的次数,fail-fast
transient int modCount;
//记录当前桶使用的个数
int threshold;
//装载因子,如果指定则使用指定的,否则使用0.75
final float loadFactor;
//hashMap的初始化函数
public HashMap(int initialCapacity, float loadFactor);
public HashMap(int initialCapacity);
public HashMap();
public HashMap(Map<? extends K, ? extends V> m);
//获得map的容量
public int size();
//判断当前Map是否为空
public boolean isEmpty();
//获得指定key的value值,通过getNode查找是否当前k是否存在,若不存在该节点则其值为空,若存在则返回其节点的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;
        //如果当前桶数组不为空,且hash出有节点
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            
            //如果第一个节点就是查找的节点,则直接返回
            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);
                
                //否则采用遍历链表的方式查找该节点是否存在
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }
//查找指定key是否存在
  public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
    }
//向集合中插入KV,若存在相同key,则覆盖其value并返回修改之前的value,如果没有则返回null
 public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
//put方法的底层实现,onlyIfAbsent控制是否改变已存在的value,false则改变已存在的value,ecict不理解
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> 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<K,V> e; K k;
            //查找是否已存在相同key,若存在,则将其存放
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;

            //如果p是红黑树的节点,则使用红黑树的put方式
            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);
                        //如果链表长度达到了8,则转换为红黑树
                        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;
                }
            }

            //如果已存在key,则依据onlyIfAbsent 判断是否能够更新value值
            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 Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0) {
            
            //如果当前桶的使用数量大于最大容量,则不可扩容
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            
            //如果扩容后在大于老的实际容量和默认容量,并且小于最大容量,则允许扩容
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
         
        //当前map未存放数据,则
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值