HashMap的无参构造函数是如何构造初始容量为16的容器的?

HashMap无参构造函数如下:

    /**
     * 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; // all other fields defaulted
    }

它是如何像它Javadoc中说的一样构造了一个初始容量为16的容器的?Node数组都不用初始化的么?至少加上一句

table = new Node<>[DEFAULT_INITIAL_CAPACITY];

才合乎常理吧!
请各位赐教!

阅读 2.9k
1 个回答

注释说了在第一次使用的时候才会初始化

  /**
     * The table, initialized on first use, and resized as
     * necessary. When allocated, length is always a power of two.
     * (We also tolerate length zero in some operations to allow
     * bootstrapping mechanics that are currently not needed.)
     */
    transient Node<K,V>[] table;

初始化代码在 final Node<K,V>[] resize() 方法里面,


     Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
     table指向这个newTab
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题