Collection與Map
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIvwFN2ETMvwVblRXavwVZsNWa0JXYvwlN18CXyV2c19CXt92YuAHawxWbs5yd3d3Lc9CX6MHc0RHaiojIsJye.jpg)
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIvwFN2ETMvwVblRXavwVZsNWa0JXYvwlN18CXyV2c19CXt92YuAHawxWbs5yd3d3Lc9CX6MHc0RHaiojIsJye.jpg)
備注:圖中隻列出了主要容器,仍有一部分容器沒有列出
EnumSet為抽象類,RegularEnumSet與JumboEnumSet是它僅有的兩個子類
Collections下的 checked 容器、synchronized 容器與 unmodifiable 容器沒有列出。Map下還有WeakHashMap子類沒有列出。
HashSet 有序輸出問題
看下面一個例子,猜一下它的輸出:
public class IteratorTest {
public static void main(String[] args) {
Random rand = new Random(47);
Set intSet = new HashSet<>();
for (int i = 0; i < 10000; i++) {
intSet.add(rand.nextInt(30));
}
for (Integer num : intSet) {
System.out.print(num + " ");
}
}
}
輸出結果(基于JDK8):0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
你可能會說,這不是有序的嗎?
事實上,對于HashSet,Iterator不保證有序,這和保證無序是有差別的。對于LinkedHashSet,支援按插入順序周遊;對于TreeSet,支援按二叉樹周遊。
對于這個例子來說,在不同版本的JDK版本中輸出可能結果有所不同。HashSet内部采用HashMap來存儲,在 jdk 8 中,hash算法有了一些改變,是以才見到了有序的結果。
對上面的例子做一下修改:public class IteratorTest {
public static void main(String[] args) {
Random rand = new Random(47);
Set intSet = new HashSet<>();
for (int i = 0; i < 10000; i++) {
intSet.add(rand.nextInt(30) + (1 << 16));
}
for (Integer num : intSet) {
System.out.print(num - (1 << 16) + " ");
}
}
}
輸出結果(基于JDK8):1 0 3 2 5 4 7 6 9 8 11 10 13 12 15 14 17 16 19 18 21 20 23 22 25 24 27 26 29 28
參考連結: