【HashMap】
特点:
1、数据插入是无序的
2、键不能重复,值可以重复
3、键可以为null,值可以为null
插入元素:hashMap.put();
获取元素: String lisi = hashMap.get(“2”);
删除元素:hashMap.remove(null);
常用方法:
int size(); map中存储键值对的个数
boolean isempty(); 判断集合是否为空
boolean containsKey(Object key); 判断集合中是否存在
boolean containsValue(Object value); 判断值是否存在
void putAll(Map m); 将Map集合添加至该集合中
void clean(); 清除集合
对map集合的遍历:3种遍历方法
//通过键值对遍历 void clean()
//先将HashMap实例转化为set实例(类型map.entry())
Iterator> iterator = hashMap.entrySet().iterator();
while(iterator.hasNext()) {
Map.Entry next = iterator.next();
String key = next.getKey();
String value = next.getValue();
System.out.print(key + ":" + value + " ");
}
System.out.println("============");
//通过键来对Map进行遍历
//仅仅对键进行访问
Iterator iterator1 = hashMap.keySet().iterator();
while(iterator1.hasNext()) {
String next = iterator1.next();
System.out.println(next+" ");
}
System.out.println("==============");
//通过值来对Map集合进行遍历
Iterator iterator2 = hashMap.values().iterator();
while(iterator2.hasNext()) {
String next = iterator2.next();
System.out.println(next+" ");
}
HashMap的应用场景:
源码分析:
继承关系:
public class HashMap extends AbstractMap
implements Map, Cloneable, Serializable {
继承了AbstractMap(jdk1.2之后)
实现了Map 接口,此实现提供所有可选的映射操作,并允许使用 null 值和 null 键
实现了Cloneable接口提供的方法,Serializable说明该类能够被序列化 ,能够被克隆、序列化
得注意的是HashMap不是线程安全的,如果想要线程安全的HashMap,可以通过Collections类的静态方法synchronizedMap获得线程安全的HashMap
Map map = Collections.synchronizedMap(new HashMap());
底层数据结构: 基于数组和链表来实现的
基本属性:
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
哈希表中数组默认初始值大小为16
static final int MAXIMUM_CAPACITY = 1 << 30;
哈希表中数组最大容量值
static final float DEFAULT_LOAD_FACTOR = 0.75f;
默认的加载因子-》扩容使用
static final Entry[] EMPTY_TABLE = {};
transient Entry[] table = (Entry[]) EMPTY_TABLE;
static class Entry{
final K key; //键值对的key
V value; //键值对的value
Entry next; //next节点
int hash; //和key相关的hash
}
transient int size;
hashMap中存储entry实体的个数
int threshold;
扩容的阈值=》capacity * loadFactor
final float loadFactor;
加载因子
HashMap底层的实现是数组+链表
实现:数组中存储的是一个个entry实体,hash到同一个索引位置的数据通过链表链接起来构造函数
//指定初始容量,指定加载因子
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();
}
//通过默认加载因子和默认容量初始化
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
//通过map集合来初始化当前集合
public HashMap(Map m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
CRUD方法研究
put方法添加元素:
public V put(K key, V value) {
//第一次插入元素,需要对数组进行初始化:注意:数组大小为2的指数关系
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
//可以存储key为null的情况
if (key == null)
return putForNullKey(value);
//key不为null
//通过key来哈希找到该数据所存在的索引位置:key相关的哈希值
int hash = hash(key);
int i = indexFor(hash, table.length);
//遍历该位置i下面的链表:(判断key是否存在,存在替换value,不存在创建新entry)
for (Entry e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}
插入key为null情况
key为null做特殊处理,存储在table索引位0号位置
遍历该位置下的链表,查看key为null的节点是否存在,存在即将value更新为传入的value
若该链表下不存在则创建新的entry节点插入该链表
private V putForNullKey(V value) {
for (Entry e = table[0]; e != null; e = e.next) {
if (e.key == null) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(0, null, value, 0);
return null;
}
final int hash(Object k) {
int h = hashSeed;
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
h ^= k.hashCode();
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
static int indexFor(int h, int length) {
// assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
return h & (length-1);
}
length 16
1001 1111 0110 0110
0000 0000 0000 1111
-------------------
0000 0000 0000 0110
==>6
void addEntry(int hash, K key, V value, int bucketIndex) {
newCapacity(table.length) *loadFactor
if ((size >= threshold) && (null != table[bucketIndex])) {
//扩容
resize(2 * table.length);
//更新新插入元素的索引位置
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}
createEntry(hash, key, value, bucketIndex);
}
扩容时机:当前存储元素的个数size>=扩容阈值threshold时考虑扩容
扩容大小为2倍的数组大小table.length(数组要满足2的指数级关系)
void resize(int newCapacity) {
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}
Entry[] newTable = new Entry[newCapacity];
transfer(newTable, initHashSeedAsNeeded(newCapacity));
table = newTable;
threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
}
创建新的table数组,并且将原来集合上的元素全部进行hash,找到新的对应位置进行插入
void transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
for (Entry e : table) {
while(null != e) {
Entry next = e.next;
if (rehash) {
e.hash = null == e.key ? 0 : hash(e.key);
}
int i = indexFor(e.hash, newCapacity);
e.next = newTable[i];
newTable[i] = e;
e = next;
}
}
}
void createEntry(int hash, K key, V value, int bucketIndex) {
Entry e = table[bucketIndex];
table[bucketIndex] = new Entry<>(hash, key, value, e);
size++;
}
元素作为当前索引位置的头部元素进行插入
获取元素get():通过键值key来查找value
public V get(Object key) {
if (key == null)
return getForNullKey();
Entry entry = getEntry(key);
return null == entry ? null : entry.getValue();
}
1、判断key是否为null,是则特殊处理,知道到0号索引位置查找元素
2、先通过hash找到索引位置,通过索引位置找到当前链表,通过判断key是否相等找到value进行返回
final Entry getEntry(Object key) {
if (size == 0) {
return null;
}
int hash = (key == null) ? 0 : hash(key);
for (Entry e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash &&((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
return null;
}
remove:删除元素
public V remove(Object key) {
Entry<K,V> e = removeEntryForKey(key);
return (e == null ? null : e.value);
}
final Entry<K,V> removeEntryForKey(Object key) {
if (size == 0) {
return null;
}
int hash = (key == null) ? 0 : hash(key);
int i = indexFor(hash, table.length);
Entry<K,V> prev = table[i];
Entry<K,V> e = prev;
while (e != null) {
Entry<K,V> next = e.next;
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
modCount++;
size--;
if (prev == e)
table[i] = next;
else
prev.next = next;
e.recordRemoval(this);
return e;
}
prev = e;
e = next;
}
return e;
}
HashMap和HashTable的异同点
相同点:
1、底层数据结构都为数组+链表
2、key都不能重复
3、插入元素有不能保证插入有序
4、哈希过程通过key进行hash
不同点:
1、安全性问题
HashMap不能保证线程安全
HashTable能保证线程
2、继承关系
HashMap继承自AbstractMa
pHashTable继承自Dictionary
3、null值问题
HashMap的key和value都可以为null
HashTable的key和value都不能为null
4、扩容方式
HashMap按照2table.length
HashTable按照2table.length+1
5、默认值
HashMap默认数组大小为16
HashTable默认数组大小为11
6、hash算法不同
7、效率不同
HashMap在单线程小效率高
HashTable在单线程小效率低