Java集合-HashMap
Java的HashMap是一种基于哈希表实现的数据结构,用于存储键值对。在HashMap中,每个键都映射到一个值。
HashMap源码分析
成员变量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
这三个变量分别是 默认的初始容量,最大容量,以及默认的加载因子 公式如下: 扩容阈值=数组容量*加载因子
/**
* 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;
/**
* Holds cached entrySet(). Note that AbstractMap fields are used
* for keySet() and values().
*/
transient Set<Map.Entry<K,V>> entrySet;
/**
* The number of key-value mappings contained in this map.
*/
transient int size;
/**
* The number of times this HashMap has been structurally modified
* Structural modifications are those that change the number of mappings in
* the HashMap or otherwise modify its internal structure (e.g.,
* rehash). This field is used to make iterators on Collection-views of
* the HashMap fail-fast. (See ConcurrentModificationException).
*/
transient int modCount;
/**
* The next size value at which to resize (capacity * load factor).
*
* @serial
*/
// (The javadoc description is true upon serialization.
// Additionally, if the table array has not been allocated, this
// field holds the initial array capacity, or zero signifying
// DEFAULT_INITIAL_CAPACITY.)
int threshold;
/**
* The load factor for the hash table.
*
* @serial
*/
final float loadFactor;
table
是哈希表的核心数据结构,它存储了键值对的桶(buckets),每个桶可以包含一个链表或红黑树,用于解决哈希冲突。在 HashMap 或 Hashtable 这类哈希表的实现中,table
是用于存储实际键值对的地方。
使用 transient
修饰 table
字段通常是因为在对象序列化时,哈希表的内部状态不需要被序列化。这是因为在反序列化时,哈希表可以根据其他序列化的信息(如容量、负载因子等)来重新构建。如果 table
不被标记为 transient
,那么在序列化和反序列化过程中,可能会导致不必要的数据传输和资源浪费,因为 table
可能很大,不需要被序列化和反序列化。
transient Set<Map.Entry<K, V>> entrySet;
: 这个字段用于缓存entrySet()
,也就是哈希表中的键值对集合
transient int size;
: 这个字段用于存储哈希表中键值对的数量,表示哈希表的大小。
transient int modCount;
: 这个字段用于记录结构性修改的次数。结构性修改是指那些改变哈希表的键值对数量或修改其内部结构的操作,例如重新哈希。modCount
用于使对哈希表的 Collection 视图(如迭代器)进行快速失败(fail-fast)处理,以便在并发环境下及时检测到其他线程的修改。
int threshold;
: 这个字段存储下一次需要调整哈希表大 小的阈值,通常是容量乘以负载因子。当键值对数量达到这个阈值时,哈希表会进行扩容。
final float loadFactor;
: 这个字段存储了哈希表的负载因子。负载因子是一个在扩容时用于确定新容量的参数。
构造函数
/**
* 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);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
/**
* 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 default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
/**
* Constructs a new <tt>HashMap</tt> with the same mappings as the
* specified <tt>Map</tt>. The <tt>HashMap</tt> is created with
* default load factor (0.75) and an initial capacity sufficient to
* hold the mappings in the specified <tt>Map</tt>.
*
* @param m the map whose mappings are to be placed in this map
* @throws NullPointerException if the specified map is null
*/
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
-
public HashMap(int initialCapacity, float loadFactor)
: 这个构造函数用于创建一个空的HashMap
,并允许指定初始容量和负载因子。初始容量表示哈希表的初始大小,负载因子表示在扩容之前哈希表的容量利用率。如果初始容量为负数或负载因子为非正数,将抛出IllegalArgumentException
异常。 -
public HashMap(int initialCapacity)
: 这个构造函数允许指定初始容量,但负载因子使用默认值(0.75)。如果初始容量为负数,将抛出IllegalArgumentException
异常。 -
public HashMap()
: 这个构造函数创建一个空的HashMap
,使用默认的初始容量(16)和负载因子(0.75)。 -
public HashMap(Map<? extends K, ? extends V> m)
: 这个构造函数允许你创建一个新的HashMap
,其初始内容是由给定的Map
对象m
提供的。这个构造函数使用默认的负载因子(0.75)和足够容纳m
中所有键值对的初始容量。
在这些构造函数中,loadFactor
表示了哈希表的负载因子,它是在哈希表需要扩容时触发的阈值。initialCapacity
是哈希表的初始容量,这是哈希表的桶数,可以在后续的操作中动态调整。DEFAULT_LOAD_FACTOR
是默认的负载因子值(0.75),MAXIMUM_CAPACITY
是哈希表的最大容量限制。