Java源码阅读之HashMap(1)

表结构的第一部分,HashMap。

/**
  * HashMap是基于Map接口的实现类,允许克隆和序列化操作。
  * HashMap是非线程安全的,键和值都允许为null,但是键为null的键值对会被放在最前面。
  * HashMap不能保证存储的键值对的顺序是一直保持不变的。
  * HashMap的操作性能与两个因素有关,桶的大小和负载因子的大小,为了保证性能,请不要负载因子设置的过小,
  * 或者在初始化的时候将桶设置的过大。
  */
public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {

    private static final long serialVersionUID = 362498820763181265L; 

    /**
     * 默认初始化桶的大小 16
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; 


    /**
     * 桶的最大容量 2的30次幂
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;


    /**
     * 负载因子,当桶内的元素比例达到该值的时候就会进行扩容
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;


    /**
     * 当桶内节点的数量超过这个值,HashMap的数据结构会由链表转换为红黑树
     */
    static final int TREEIFY_THRESHOLD = 8;


    /**
     * 当桶内节点的数量小于这个值的时候,HashMap的数据结构会由红黑树转换为链表
     */
    static final int UNTREEIFY_THRESHOLD = 6;


    /**
     * 桶的数据结构转化为红黑树时table的最小值
     */
    static final int MIN_TREEIFY_CAPACITY = 64;


    /**
     * HashMap底层的基本组成元素,用于存储键值对
     */
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;    // 存储key的hash值
        final K key;       // key值
        V value;           // 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的hash值
        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }


        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

            // 判断当前节点与o是否相等,如果o和当前节点不是同一个对象,必须两者
            // key和value同时相等才算o和当前节点相等
        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值
     */
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }


    /**
     * 如果x实现了Comparable接口,那么返回x的类类型,否则返回null
     */
    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;
    }


    /**
     * 如果k和x属于同一个类的对象,返回k.compareTo(x)的结果,否则返回0
     */
    @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
    static int compareComparables(Class<?> kc, Object k, Object x) {
        return (x == null || x.getClass() != kc ? 0 :
                ((Comparable)k).compareTo(x));
    }


    /**
     * 如果cap为2的幂,那么返回cap否则返回大于cap的最小的一个2的幂
     */
    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;
    }

    /**
     * HashMap初始化后首次使用存储键值对的数组。
     */
    transient Node<K,V>[] table;


    /**
     * 用于存放键值对的集合
     */
    transient Set<Map.Entry<K,V>> entrySet;


    /**
     * 当前对象包含的键值对数量。
     */
    transient int size;


    /**
     * 这个集合被修改过的次数。
     */
    transient int modCount;


    /**
     * 下一个需要调整桶大小的值,当键值对数量达到此值时需要进行扩容(容量*负载因子)
     */    
    int threshold;


    /**
     * 负载因子,非默认
     */
    final float loadFactor;

    /**
     * 构造函数,需要指定初始化桶大小和负载因子大小
     */
    public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);   // 下次扩容的大小
    }


    /**
     * 构造函数,指定初始化桶大小
     */
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }


    /**
     * 构造函数,使用默认桶大小和默认负载因子
     */
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
    }


    /**
     * 使用m的键值对构造一个新的hashMap对象,负载因子为默认负载因子,桶的大小为至少容纳下m的键值对
     */
    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }


    /**
     * 将m中的键值对存入当前HashMap对象中
     */
    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            if (table == null) { // 计算下次扩容需要增加多大空间
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                if (t > threshold)
                    threshold = tableSizeFor(t);
            }
            else if (s > threshold)
                resize(); //如果m的大小大于下次扩容需要增加的空间,重新进行扩容
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);
            }
        }
    }


    /**
     * 返回当前HashMap对象中存储的键值对数量
     */
    public int size() {
        return size;
    }


    /**
     * 判断当前HashMap对象是否为空
     */
    public boolean isEmpty() {
        return size == 0;
    }


    /**
     * 给定key值,从当前HashMap对象中取出Key对应的value值
     */
    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }


    /**
     * 根据给定的hash和key值获取节点信息,适用于hash冲突的时候
     */
    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) {
            if (first.hash == hash && // 检查第一个节点是否符合条件
                ((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;
    }

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值