Set
無序 不重複
使用HashSet 主要用來 去重
HashSet<String> set = new HashSet<>();
set.add("a");
set.add("a");
set.add("b");
set.add("b");
set.add("c");
set.add("c");
System.out.println(set);
結果
[a, b, c]
注意: HashSet 自定義對象類型的時候 是不一定能夠將自定義對象去重 的 因爲系統不知道自定義對象傳進來的對象是幾個對象 或者按照怎樣的規則來確定是否重複 這時候需要 通過重寫對象類的 equals 和 HashCode方法 達到去重的效果
重寫HashCode方法
Set集合在存儲的時候
當HashCode值相同時
會調用equals方法 進行對比
當HashCode值不相同時 認爲不是同一個對象
沒有調用equals方法
LinkedHashSet
是 HashSet的一個子類
特點: 有序(怎麼存怎麼取) 不重複
TreeSet(內部二叉樹實現)
無序(不按存儲順序取出) 不重複 無下標
主要作用 排序
TreeSet<Integer> set = new TreeSet<>();
set.add(1);
set.add(7);
set.add(1);
set.add(9);
set.add(5);
for (Integer integer : set) {
System.out.println(integer);
}
結果
1
5
7
9
注意: TreeSet集合在保存自定義對象類型的時候 系統是不知道排序規則的 但是 系統留了一個接口Comparable 通過TreeSet排序 需要實現這個接口 寫排序規則
給哪個對象排序 那個對象就實現接口Comparable
或者 也可以通過創建一個比較器類 來寫排序規則
讓比較器實現接口Comparable 然後把比較器傳入TreeSet集合