美文网首页
HashMap的小秘密

HashMap的小秘密

作者: fatboy9 | 来源:发表于2018-09-23 23:28 被阅读0次

Api文档里说:

An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created.

代码是这样的:

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);
}
 
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;
}

也就是说,intialCapacity出了构造方法就没用了,它也没被记下来。被记下来的是this.threshold = tableSizeFor(initialCapacity)。以后第一次put()时,用的是这个threshold来初始化bucket数组。tableSizeFor(c)返回最小的数t,t大于等于c且t是2的整数次幂。

代码写的和文档说的不一样……而且你不看代码是不会知道这件事的。比如用9、10、11、12、13、14、15、16作为initialCapacity来初始化,效果是完全一样的!

这种事,也很难说算是个什么事。但作为用Java的人,总是不免觉得别扭。把代码写的和文档一样又不是很难,也是应该的。何必要这样呢?

相关文章

  • HashMap的小秘密

    Api文档里说: An instance of HashMap has two parameters that a...

  • HashMap了解一下

    前言 HashMap HashMap类继承图 HashMap属性 HashMap构造函数HashMap(int i...

  • HashMap源码

    eg: HashMap hashMap = new HashMap<>(); hashMap.put(1,"QG...

  • HashMap源码理解

    HashMap理解 HashMap定义 HashMap实现机制 HashMap与HashTable的主要区别 关键...

  • 【16】 hashmap

    hashmap 1.7 和1.8的区别 hashmap全家桶 hashmap 源码解析 hashmap hashm...

  • 2018-03-12

    HashMap in Java HashMap in Redis HashMap in Golang

  • Java-HashMap 精讲原理篇

    本文涉及HashMap的: HashMap的简单使用 HashMap的存储结构原理 HashMap的扩容方法原理 ...

  • HashMap剖析

    Java集合:HashMap源码剖析 一、HashMap概述 二、HashMap的数据结构 三、HashMap源码...

  • HashMap源码解析JDK8

    一、HashMap基础 1.1 HashMap的定义 我们先看一下HashMap的定义: 1.2 HashMap的...

  • HashMap 的构造函数分析

    HashMap 系列文章 HashMap 的自定义常量分析 HashMap 的构造函数分析 HashMap 的 h...

网友评论

      本文标题:HashMap的小秘密

      本文链接:https://www.haomeiwen.com/subject/hptcoftx.html