HashMap features
- The bottom layer of HashMap is array + linked list + red-black tree (JDK 1.8)
- HashMap is stored in key-value form, where key can be allowed to be null but can only be one, and key does not allow duplication.
- HashMap is thread insecure.
- The order in which HashMap is stored and traversed may be inconsistent.
- When HashMap saves data, it determines the location of storage by calculating the hash value of the key.
attribute
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
//The default initial capacity is 16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
//Maximum capacity
static final int MAXIMUM_CAPACITY = 1 << 30;
//The default load factor is 0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//Hash array (initialized in resize()
transient Node<K,V>[] table;
//ket-value set
transient Set<Map.Entry<K,V>> entrySet;
//Element number
transient int size;
//Modification times
transient int modCount;
//Capacity threshold (element number will automatically expand if exceeding this value)
int threshold;
//Load factor
final float loadFactor;
- When the number of elements exceeds threshold (capacity threshold), HashMap performs capacity expansion operations.
- threshold = size * loadFactor
Construction method
/*No ginseng*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;//Default load factor
}
/*Initial incoming capacity*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/*Input Initial Capacity and Load Factor*/
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);
}