Map接口与Collection接口不同,这个接口的元素是“键值对”,键不可以重复,值可以重复。它的实现类, HashMap HashTable LinkedHashMap
hashMap的特点是在判断键是否重复的时候采用哈希算法,因此要求作为HashMap键的对象,必须重写equals和hashCode方法,我们来看一下源码
public static void main(String[] args) {
Map<String, String> map = new HashMap<String,String>();
map.put("1992", "荷兰");
}
当我们new 一个HashMap的时候
/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}
/**
* 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;
threshold = initialCapacity;
init();
}
这两个参数为
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
原来new 一个HashMap的时候,会创建一个长度为Capacity的数组,默认长度为
1 << 4
左移4位,即2的4次幂,初始长度为16,初始负载因子为 0.75f ,这个数组可以存储元素的位置称为“bucket”,每个bucket都有下标,所以当我们要往进put的时候,它的顺序应该是这样的。
1.先求出键对象的hashCode
2.求出下标,用hashCode跟Capacity长度求模,算出来的就是坐标
3.如果坐标没有元素,直接插入,如果坐标有元素,这个时候才触发equals方法
4.如果相等,进行替换,如果不相等,往下一坐标插入元素。
那负载因子有什么用呢,我们都知道数组长度是固定的,刚开始默认设置长度为16,如果不够的话就要进行扩容,扩容为200,这里设定的是,当元素个数超过 长度*负载因子的时候就要扩容,例如 默认长度为16,负载因子为0.75,即元素个数>12的时候就要扩容,
Entry[] newTable = new Entry[newCapacity];
HashTable也是Map的一个实现,它跟HashMap的区别有点类似 ArrayList 和 vector的区别
HashTable:
1.重量级,线程安全,效率低
2.null作为键或者值会抛异常
HashMap:
1.轻量级,线程不安全,效率高
2.允许null作为键或者值