结论:HashSet跟添加元素顺序无关,但是内部有固定顺序,是按hash顺序存储。
package com.example.demo.java;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.Set;
@Slf4j
public class HashSetDemo {
@Test
public void hashSetDemo(){
Set hashSet = new HashSet();
hashSet.add(1);
hashSet.add(3);
hashSet.add(2);
hashSet.add("c");
hashSet.add("b");
hashSet.add("a");
hashSet.add("d");
log.info(hashSet.toString());
for (Object it:hashSet){
log.info(it.toString());
}
}
}
输出顺序是固定的:
23:25:03.812 [main] INFO com.example.demo.java.HashSetDemo - [1, a, 2, b, 3, c, d]
23:25:03.812 [main] INFO com.example.demo.java.HashSetDemo - 1
23:25:03.812 [main] INFO com.example.demo.java.HashSetDemo - a
23:25:03.812 [main] INFO com.example.demo.java.HashSetDemo - 2
23:25:03.812 [main] INFO com.example.demo.java.HashSetDemo - b
23:25:03.812 [main] INFO com.example.demo.java.HashSetDemo - 3
23:25:03.812 [main] INFO com.example.demo.java.HashSetDemo - c
23:25:03.812 [main] INFO com.example.demo.java.HashSetDemo - d
如果你希望乱序输出,恐怕要让你失望了。无论怎么修改添加元素的顺序。都只有上面一种输出顺序。
源码:
/**
* 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<>();
}
创建一个HashSet实际上是创建了HashMap。
/**
* Adds the specified element to this set if it is not already present.
* More formally, adds the specified element <tt>e</tt> to this set if
* this set contains no element <tt>e2</tt> such that
* <tt>(e==null ? e2==null : e.equals(e2))</tt>.
* If this set already contains the element, the call leaves the set
* unchanged and returns <tt>false</tt>.
*
* @param e element to be added to this set
* @return <tt>true</tt> if this set did not already contain the specified
* element
*/
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
添加一个元素的时候,把元素当key,new Object为value。添加到map中这样保证了Set的值唯一的特性。
接下来就是HashMap那一套了。添加元素源码如下:
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
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))))
//1.如果key相等,且hash值相等,则替换掉
e = p;
else if (p instanceof TreeNode)
//2.1如果 p是TreeNode的实例。表示是红黑树,直接插入红黑树中
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {//2.2 不是TreeNode,表示是链表,则放在链表的最末端
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
//当链表长度达到8时,改为红黑树结构
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;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
HashMap中元素的存储有可能有两种形式,红黑树或者链表,当链表大小达到8时,转为红黑树存储。
两种数据结构添加节点的关键方法:
链表:p.next = newNode(hash, key, value, null);
红黑树:e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);