2.从类的层次看HashMap
HashMap实现Map接口,属于集合框架中Map的一种实现,主要使用key和value存储数据。存储的元素key是不可以重复,重复的情况下,进行覆盖。
HashMap 属于线程不安全的类,在并发的情况下。同一时刻同一个HashMap,一个线程向HashMap 中put元素,另一个线程迭代HashMap中的元素会产生fast fail。程序会抛出异常。
3.构造函数以及常用的Api
3.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; // all other fields defaulted
}
无参构造函数,初始化HashMap哈希表默认的长度为16 负载因子为0.75
/**
* 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 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);
}
传入实现Map的集合类,可以完成集合中数据的复制。
3.2 常用api
3.2.1 HashMap 主要用于数据的增删改查,所以常用的Api主要按照增删改查进行分类
增加元素: put(K key, V value),putAll(Map<? extends K, ? extends V> m)
删除元素:remove(Object key),remove(Object key, Object value),clear()清空元素
修改元素:值覆盖的方式修改value,直接使用put(K key, V value)方法,replace(K key, V value),replace(K key, V oldValue, V newValue)。
查询:(1)查询容器本身:size(),isEmpty(),(2)查询容器中的元素:get(Object key), entrySet() , keySet(),values() 。
4. 源码追踪
4.1 put 元素的过程
/**
* 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) {
return putVal(hash(key), key, value, false, true);
}