1. Set集合
1.1 Set集合概述
特徵:
無序,不可重複
無序:添加順序和存儲順序不一致,【不代表有排序效果】
不可重複: 在一個Set集合中不能出現相同元素
interface Set<E>
--| class HashSet<E> 底層是哈希表存儲數據
--| class TreeSet<E> 底層存儲數據是一個二叉樹
1.2 HashSet
1.2.1 底層結構
package com.qfedu.b_set;
import java.util.HashSet;
public class Demo2 {
public static void main(String[] args) {
HashSet<Person> hashSet = new HashSet<Person>();
Person p1 = new Person(1, "寶哥", 10);
Person p2 = new Person(2, "大熊", 15);
Person p3 = new Person(3, "騷磊", 2);
Person p4 = new Person(4, "騷傑", -5);
Person p5 = new Person(5, "林妹妹", 11);
Person p6 = new Person(6, "康爺", 8);
Person p7 = new Person(6, "康牙", 10);
hashSet.add(p4);
hashSet.add(p6);
hashSet.add(p3);
hashSet.add(p5);
hashSet.add(p2);
hashSet.add(p1);
hashSet.add(p7);
System.out.println(hashSet);
}
}
1.3 TreeSet
1.3.1 Tree樹形結構
1.3.2 TreeSet存儲方式
沒有比較方式無法存儲
1.3.3 Comparable接口使用
interface Comparable<T> {
int compareTo(T t);
}
方法參數爲T類型,由實現類遵從接口時約束,
compareTo方法,返回值類型int類型,0, 負數,正數
0 表示兩個元素一致,如果在TreeSet中比較結果爲0,表示同一個元素,無法存儲第二個。
Comparable接口由存儲元素對應的類遵從,完成該方法
1.3.4 Comparator接口使用
interface Comparator<T> {
int compare(T o1, T o2);
}
需要完成一個自定義比較器類對象,
int 返回值 0,負數,正數
0 表示兩個元素一致,如果在TreeSet中比較結果爲0,表示同一個元素,無法存儲第二個。
1.3.5 Comparator使用要高於Comparable使用