我们都知道Set的集合是无序集合的,但是有时却会出现有序;HashSet/HashMap一起说是因为HashSet底层实现就是HashMap
HashSet<Integer> hashSet = new HashSet<>();
hashSet.add(3);
hashSet.add(1);
hashSet.add(7);
hashSet.add(5);
hashSet.add(4);
System.out.println(hashSet);//[1,3,4,5,7]
而:
HashSet<Integer> hashSet = new HashSet<>();
hashSet.add(12);
hashSet.add(15);
hashSet.add(17);
hashSet.add(66);
hashSet.add(2);
System.out.println(hashSet);//[17,66,2,12,15]
同样是无序输入,为什么一个有序输出,一个无序输出呢?
首先我们查看HashSet的源码
public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable
{
static final long serialVersionUID = -5024744406713321676L;
private transient HashMap<E,Object> map;
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
/**
* Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
* default initial capacity (16) and load factor (0.75).
*/
public HashSet() {
map = new HashMap<>();
}
public boolean add(E e) {
//为了保证元素唯一性,元素是作为HashMap的key来保存的 PRESENT是一个虚值,至始至终都是不变
return map.put(e, PRESENT)==null;
}
}
可以很明显的看到其实HashSet的底层是使用HashMap来实现,可以说是基于HashMap来实现的,为了保证元素唯一性,元素是作为HashMap的key来保存的
所以为什么可以与HashMap一起说
使用hashMap上面的问题同样是有,归根到底还是得查看HashMap的源码;
查看这两个官方的Api同样是有一句话
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
- 它不保证集合的迭代顺序。特别是,它不能保证顺序会随着时间的推移保持恒定。
关键之处我们可以进入HashMap中的put方法
/**
* 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
}
- default initial capacity(16) and the default load factor (0.75).
在HashMap的构造函数啥我们可以看到:初始大小为16,load factor (0.75):负载因子,当map填满了75%的bucket(哈希表)时候,将会创建原来HashMap大小两倍的bucket数组
HashMap的put方法源码:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
可以看到首先我们需要将key转化成哈希值,当然HashSet直接将元素当作键
查看hash方法
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
@Override
public int hashCode() {
return Integer.hashCode(value);
}
public static int hashCode(int value) {
return value;
}
通过hashCode()可以看到,如果键是Integer的话,hash值就是其本身
而:(h = key.hashCode()) ^ (h >>> 16) 这条公式:key.hashCode()与key.hashCode()>>>16进行异或操作,因为16bit不够,高16bit补0,与0异或是它本身,所以这条语句是key.hashCode()高16bit不变,低16bit异或与;这样做法也是为了减少碰撞率
如果我们传入的键是是整型也就是hash(key)=key,所以这条公式就是key = key ^ (key >>> 16)
接下来看HashMap的put方法
/**
* Implements Map.put and related methods.
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
//tab是节点数组,n表示tab的长度
Node<K,V>[] tab; Node<K,V> p; int n, i;
//第一次插入初始化
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//这里进行元素分配,分配到tab[i],i= (n - 1) & hash]
//==null 且没有冲突,节点为空直接插入节点
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
//有冲突
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
//如果插入的位置有元素,就把这个元素的next指针指向自己
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
// 记录修改次数:HashMap内容的修改都将增加这个值。迭代器初始化过程中会将这个值赋给迭代器的expectedModCount,在迭代过程中,判断modCount跟expectedModCount是否相等,如果不相等就表示已经有其他线程修改了Map,马上抛出异常
++modCount;
if (++size > threshold)
resize();//扩容操作
afterNodeInsertion(evict);
return null;
}
在put可以看到元素put进来,要==先进行运算得到位置i= (tab.length - 1) & hash,==且当(++size > threshold),也就是size大于阈值threshold时,HashSet就会自动扩容resize()。
- threshold= capacity * load factor,默认情况的话threshold=16*0.75=12
进入resize方法:
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//oldThr=12
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//newCap = oldCap << 1 = oldTab.length*2
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold,
}
......
//设置新阈值
threshold = newThr;
}
- newThr = oldThr << 1; // double threshold,右移1位:
- //设置新阈值threshold = newThr;
新的长度扩大到原来的两倍了,切阈值也是两倍
所以HashMap在默认的情况下,如果插入的整型数量大于12,24…时(默认大小*阈值),会自动扩容16,32…
此时我们就可推算出位置i的位置
i = (tab.length - 1) & key
整型的hash值就是其本身
1:当元素的数量<=12,长度为默认16,并未扩容,插入整型元素(0-15)
- i=(16-1)&(0~15)=(0~15)15&任何0 ~ 15的数都是他本身。
- 所以插入整型元素数量小于等于12个,在0~15的数都是其本身的位置 ,遍历输出会得到有序
1:当元素的数量<=12,长度为默认16,并未扩容,插入整型元素(16-31) - i=(16-1)&(16~31)=(0~15)16~31的位置i都是在0~15
此时我们可以得出一个结论:当HashSet插入整型元素的数量 <= 12时,此时HashMap的length=16,
每隔length-1,i会在0~15周期循环
2:当元素的数量大于12下于24
- 此时因为数量大于阈值,所以HashMap会扩容值32,如果我们插入的元素都在(0-31)范围
- i = (32 - 1) & (0 ~ 31) = (0 ~ 31) 所以 任何0 ~ 31的数都是他本身。
此时我们可以得出结论:当插入整型元素时,元素的下标 i 根据元素的大小,每隔length-1,从0到length-1周期性循环。而length会动态扩容,这就需要我们根据我们插入元素的数量来决定
理论上的得出来了,验证看是否正确,
比如插入12,88,32,2,6
首先我们插入的数量是<12,不会触发阈值,此时的length长度默认16。每隔16-1,从0到16-1周期性循环
- 插入12,12%15=i=12, 所以12在12的位置上
- 插入88,88%15=i=13,所以88在13的位置上
- 插入32,32%15=i=2,所以32在2的位置上
- 插入2,2%15=i=2,所以2在2的位置上
- 插入6,6%15=i=6,所以6在6的位置上
所以此时HashMap中元素的位置结构:
所以推断输出结果为:32,2,6,12,88
与程序输出的一致,所以关键之处就是要通过插入元素的个数确定length
刚刚也出现了一种特殊情况,就是32的i=2;2的i也是2,重叠了,此时通过源码可以看到:
p.next = newNode(hash, key, value, null);
他是获取到了32这个节点,并且将其节点的next指针指向;
所以也可以证明这个HashMap底层的实现是又数组加链表的方式来实现;
最后正如Api所说:
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
- 它不保证集合的迭代顺序。特别是,它不能保证顺序会随着时间的推移保持恒定。
随着元素数量的增多,算法因子也会随之改变,算法确定的位置也随数量的增多而变化
查看resize()中的源码:
final Node<K,V>[] resize() {
......
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
HashMap进行数组扩容需要重新计算扩容后每个元素在数组中的位置,很耗性能