例子
package MaMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
public class HashsetOrder {
public static void main(String[] args) {
HashSet<Integer> set = new HashSet<Integer>();
set.add(5);
set.add(6);
set.add(7);
set.add(1);
set.add(2);
set.add(3);
set.add(4);
System.out.println("hashset的输出:");
for (int i = 0; i < 10; i++) {
for (Integer integer : set) {
System.out.print(integer);
}
System.out.println();
}
HashMap<Integer, Integer> map = new HashMap<Integer,Integer>();
map.put(4, 4);
map.put(5, 5);
map.put(6, 6);
map.put(1, 1);
map.put(2, 2);
map.put(3, 3);
System.out.println("hashmap的输出:");
for (int i = 0; i < 10; i++) {
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.print(entry.getValue());
}
System.out.println();
}
}
}
输出
hashset的输出:
1234567
1234567
1234567
1234567
1234567
1234567
1234567
1234567
1234567
1234567
hashmap的输出:
123456
123456
123456
123456
123456
123456
123456
123456
123456
123456
可以看到hashset的add放入顺序和hashmap的put放入顺序都不是从1开始放的,输出的顺序与放入顺序不一致,所以hash是乱序的。
但是hashset和hashmap输出了十次,如果完全无序的话应该每次输出不同的顺序,所以hashset和hashmap应该有自己的某种保存顺序规则。
下面看源码:hashset.add源码,使用的是hashmap的put,所以跟hashmap的无序保存规则是一致的。
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
看hashmap的put源码,可见先利用key计算了一下hash值
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
打开putval方法
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))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
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
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;
}
其中加红的 p = tab[i = (n - 1) & hash]) == null ,通过已经存在的数组大小和key hash做与运算,如果该位置为null,就把当前数存入。
如果p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))) 根据hash判断该位置,已经存在,判断是否跟存入的key是否相等。如果位置一致,key不相等就以Node<K,V> e方式存入在数组同一个位置。
总结:
1.因为存入的时候不是按照顺序一个个放入的,所以取出来就是相对于存入的顺序是乱序的。
2.但是它们是按照hash值等规则存入的,所以存入有自己的顺序,所以遍历取出来的时候是顺序一致的。
3.因为hashset存入是利用的hashmap的put方法,所以他们都是无序存入,自身有序且不变的。