首页 > 其他分享 >JDK1.7和JDK1.8和HashMap详解

JDK1.7和JDK1.8和HashMap详解

时间:2023-05-09 23:35:20浏览次数:40  
标签:JDK1.8 hash HashMap int JDK1.7 value key null

 近期对JDK1.7和JDK1.8的HashMap源码进行了学习,今天也在这里进行个人总结一下。首先,众所周知,HashMap是以键值对的方式存储数据的,1.7的底层数据结构是数组+链表,是一个Entry数组。1.8的底层数据结构是数组+链表+红黑树·,是一个Node对象的数组。下面我就根据源码分析下HashMap是怎么进行初始化、插入数据的。

 

JDK1.8

1.初始化。

//构造方法1
public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

 

    
//构造方法2
public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

 

//构造方法3
  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);
    }

 

构造方法主要有以上几个主要是对加载因子、阈值进行初始化。构造方法1初始化了加载因子,取默认值0.75,构造方法2初始化了阈值,默认的加载因子0.75,构造方法3初始化了阈值和加载因子。阈值的取值做了处理,取入参最小的2的幂次方的值。此时HashMap的数组还没有进行初始化,那什么时候开始初始化呢?源码在put方法的时候,如果数组为空,才进行了初始化。

 

2.HashMap的put方法

   public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
/** * 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;
        if ((tab = table) == null || (n = tab.length) == 0)
//如果数组为空或长度为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; if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) 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; } 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; }
    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
        }
        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;
    }

 

2.1.当HashMap的table为空时,就会把阈值当作容量进行初始化,然后重新根据加载因子重新计算阈值。

2.2.当HashMap的table不为空时,就计算put元素的key的下标,如果数组下标没有值,那就new一个Node对象直接插入到数组;如果key相等就覆盖;如果key不相等,就遍历这个下标的链表,如果key相等就覆盖,不相等就遍历到链表的尾部进行插入,

插入完,再判断链表的长度是否大于8,如果大于8而且数据的长度小于64,则进行数组扩容,否则就将链表转成红黑树;修改次数modCount++,长度size++,判断下如果长度大于阈值,则进行扩容;

 

JDK1.7

1.初始化

    /**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR); table = new Entry[DEFAULT_INITIAL_CAPACITY]; init(); }
    /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and the default load factor (0.75).
     *
     * @param  initialCapacity the initial capacity.
     * @throws IllegalArgumentException if the initial capacity is negative.
     */
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
    /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and load factor.
     *
     * @param  initialCapacity the initial capacity
     * @param  loadFactor      the load factor
     * @throws IllegalArgumentException if the initial capacity is negative
     *         or the load factor is nonpositive
     */
    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);

        // Find a power of 2 >= initialCapacity
        int capacity = 1;
        while (capacity < initialCapacity)
            capacity <<= 1;

        this.loadFactor = loadFactor;
        threshold = (int)(capacity * loadFactor);
        table = new Entry[capacity];
        init();
    }

1.构造方法1初始化,取了默认的加载因子0.75,阈值取了16*加载因子,初始化了一个16的数组;构造方法2初始化,取入参初始容量,取最下2的幂次方容量,默认加载因子0.75,初始化阈值,初始化数组;构造方法3同样道理;

2.插入元素

    /**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V put(K key, V value) {
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key.hashCode());
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            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;
    }
    /**
     * Offloaded version of put for null keys
     */
    private V putForNullKey(V value) {
        for (Entry<K,V> e = table[0]; e != null; e = e.next) {
            if (e.key == null) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }
        modCount++;
        addEntry(0, null, value, 0);
        return null;
    }
    /**
     * Adds a new entry with the specified key, value and hash code to
     * the specified bucket.  It is the responsibility of this
     * method to resize the table if appropriate.
     *
     * Subclass overrides this to alter the behavior of put method.
     */
    void addEntry(int hash, K key, V value, int bucketIndex) {
        Entry<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<>(hash, key, value, e);
        if (size++ >= threshold)
            resize(2 * table.length);
    }

2.1.如果key为null,则找到数组的第一个元素,遍历这个元素的链表,如果key为null,则覆盖值,否则使用头插法插入到第一个元素中,size++,如果size大于阈值,则进行2倍扩容,扩容后遍历每个元素,使用头插法重新插入;如果key不为null,

根据key的哈希计算下标,剩下的步骤和上面一样;

 

 

标签:JDK1.8,hash,HashMap,int,JDK1.7,value,key,null
From: https://www.cnblogs.com/mojianheng/p/17383996.html

相关文章

  • Centos7安装JDK1.8详细步骤
    JDK解压JDK安装文件。在终端中,进入你下载的JDK安装文件所在的目录,然后执行以下命令:tar-zxvfjdk-<版本号>-linux-x64.tar.gz其中,<版本号>是你下载的JDK版本号。这个命令将会解压JDK安装文件到当前目录中。将JDK安装文件移动到/usr/local/目录下。在终端中,执行以下命令......
  • 如何决定使用 HashMap 还是 TreeMap?
    @[toc]问:如何决定使用HashMap还是TreeMap?介绍TreeMap<k,v>的Key值是要求实现java.lang.Comparable,所以迭代的时候TreeMap默认是按照Key值升序排序的;TreeMap的实现是基于红黑树结构。适用于按自然顺序或自定义顺序遍历键(key)。HashMap<k,v>的Key值实现散列hashCode(),分布是散列的......
  • hashmap oop in golang
    packagemainimport("fmt")constHASH_BUCKET_SIZE=3//1023typehash_nodestruct{keyinterface{}valinterface{}next*hash_node}typeHASH_BUCKET[HASH_BUCKET_SIZE]*hash_nodefunchash(keyinterface{})int{h......
  • golang hashmap
    packagemainimport("fmt")constHASH_BUCKET_SIZE=3//1023typehash_nodestruct{keyinterface{}valinterface{}next*hash_node}//hashbuckettosavenodeaddressvarhash_bucket[HASH_BUCKET_SIZE]*hash_nodefunc......
  • HashMap设置初始容量一直都用错了?
    1背景今天在代码审查的时候,发现一位离职的同事留下了这样一串代码:Map<String,String>map=newHashMap<>((int)(list.size()/0.75F+1));第一反应是:又在炫技,又在搞这些花里胡哨的东西。但是看到0.75的我却陷入了沉思,稍微深入了解过Map的应该都知道,Map中有个属性,叫做负载因......
  • 简单说说HashMap和LinkedHashMap的区别
    HashMap和LinkedHashMap的区别我们知道HashMap的变量顺序是不可预测的,这意味着便利的输出顺序并不一定和HashMap的插入顺序是一致的。这个特性通常会对我们的工作造成一定的困扰。为了实现这个功能,我们可以使用LinkedHashMap。LinkedHashMap详解先看下LinkedHashMap的定义:pu......
  • Hashtable、synchronizedMap、ConcurrentHashMap 深度比较
    关键字:Hashtable、synchronizedMap、ConcurrentHashMap深度比较util.concurrent包除了包含许多其他有用的并发构造块之外,还包含了一些主要集合类型List和Map的高性能的、线程安全的实现。BrianGoetz向您展示了用ConcurrentHashMap替换Hashtable或synchro......
  • 简单聊聊,HashMap、HashTable、ConcurrentHashMap 之间的区别
    一、直观上的区别HashTable和HashMap都是用于存储键值对的数据结构我们一般把搜索的数据称之为关键字(key),与关键字key对应的为值(value),这种模型统称为“key-value的键值对”。Map和Table采用的都是key-Value模型,例如:有一个字符串,统计其中每个字符出现的次数,......
  • JDK1.8新特性(七):默认方法,真香,开动!接口?我要升级!!
    前期回顾:JDK1.8新特性(一):JDK1.8究竟有哪些新特性呢JDK1.8新特性(二):为什么要关注JDK1.8JDK1.8新特性(三):Lambda表达式,让你爱不释手JDK1.8新特性(四):函数式接口JDK1.8新特性(五):Stream,集合操作利器,让你好用到飞起来JDK1.8新特性(六):Stream的终极操作,轻松解决集合分组、汇总等复杂......
  • linux安装jdk1.8
    为防止操作权限不足,建议切换root用户,当然如果你对Linux命令熟悉,能够自主完成权限更新操作,可以不考虑此推荐。环境:centos7.6ssh连接工具:tabby(自从用了这个工具,我再也不用xshell了,这个工具自带文件上传,还有网页版)创建目录mkdir/opt/jdk把jdk的压缩包上传到/opt/jdk目录下......