1.HashMap简介
- HashMap继承了AbstractMap类该类实现了Map接口,HashMap同时实现了Map接口。
- HashMap是key,value结构的键值对,支持key和value都为null
- HashMap和HashTable功能很相近,可以把它看做非线程安全的HashTable和允许key,value为空。
2.分析下HashMap的内部结构
HashMap有两个重要的参数:一个是加载因子,另一个是初始容量
//初始容量为16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
//默认加载因子是0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;
3.HashMap的构造函数
//设置初始容量和加载因子
public HashMap(int initialCapacity, float loadFactor)
//设置初始容量和默认加载因子
public HashMap(int initialCapacity)
//默认构造,使用默认容量和默认加载引起
public HashMap()
//使用已经存在的map创建新的map
public HashMap(Map<? extends K, ? extends V> m)
4.HashMap主要对外接口
4.1 get方法
public V get(Object key) {
//如果key是null的话
if (key == null)
return getForNullKey();
//key不为空调用getEntry方法
Entry<K,V> entry = getEntry(key);
return null == entry ? null : entry.getValue();
}
private V getForNullKey() {
//判断大小
if (size == 0) {
return null;
}
//null存在table[0]上,返回value的值
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
if (e.key == null)
return e.value;
}
return null;
}
final Entry<K,V> getEntry(Object key) {
//如果map的size为0,那么就直接返回null
if (size == 0) {
return null;
}
//计算hash值
int hash = (key == null) ? 0 : hash(key);
//获取到hash值对应的table中的链表
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
//遍历该链表,判断key是否相等
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
return null;
}
5.HashMap存储数据是无序的我们看下代码的例子
HashMap<String,Integer> store = new HashMap<String,Integer>();
store.put("22", 33);
store.put("44", 44);
store.put("55", 55);
for(Map.Entry<String,Integer> ele :store.entrySet()) {
System.out.println(ele.getKey() + "--" + ele.getValue());
}
运行结果如下:
44--44
55--55
22--33
说明并不是按照我们存储的顺序存储的。