TreeSet:自動排序物件的集合
新增一個
TreeSetTest 主程式
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
30
| import java.util.*;
public class TreeSetTest {
public static void main(String[] args) {
//Set介面,不重複
//TreeSet,不重複,有排序性
Set<Integer> set = new TreeSet<>();//隨時可以將TreeSet更換為其他實作介面,只要是Set有的
/*
宣告 參考變數(set) 使用 介面(Set)而不是使用TreeSet,方便將來更換不同的集合,讓程式將來修改時更容易
Set介面可實作的類別很多,TreeSet是其中一個,之後如果修改,可以將TreeSet修改為HashSet
下面的程式碼都不需要異動
Set<Integer>指泛型,只要是Integer的類型都可以加入
*/
set.add(10);
set.add(5);
set.add(7);
set.add(3);
Set<String> set2 = new TreeSet<>();
set2.add("C");
set2.add("A");
set2.add("F");
set2.add("B");
System.out.println(set);
System.out.println(set2);
}
}
|
顯示結果
若將 Animal物件放入TreeSet
//嘗試將 Animal 物件放入 TreeSet
Animal a = new Dog();
a.setName("小白");
Animal b = new Cat();
b.setName("小花");
Animal c = new Bird();
c.setName("小飛");
Set<Animal> set3 = new TreeSet<>();
set3.add(a);
set3.add(b);
set3.add(c);
若要將動物也使用TreeSet會出現錯誤,因為動物無法排序,
將 a 加入 TreeSet ,轉型失敗, a 所操作的 Dog 物件
無法轉成 java.lang.Comparable 型別
所以會出現下面的結果
TreeSet 只接受具有 Comparable 特性的物件
所以要在
Animal 插入介面
Comparable<Animal>,並且加入自定的規則
abstract public class Animal implements 有攻擊能力的, Comparable<Animal> { // 抽象類別
@Override //定義Animal的大小判定,以下以字串名字長度為判斷標準
public int compareTo(Animal o) {
return this.name.length()-o.name.length();
/*
可將下面判斷方式簡化,若要由大排到小,將運算結果前面加上負號即可
return -(this.name.length()-o.name.length());
*/
// if (this.name.length() > o.name.length()) {
// return 0;
// } else if (this.name.length() > o.name.length()) {
// return -1;
// } else {
// return 0;
// }
/*
返回:負整數、零或正整數,根據此物件是小於、等於還是大於指定物件。
*/
}
}
再次執行TreeSet
//嘗試將 Animal 物件放入 TreeSet
Animal a = new Dog();
a.setName("小白A");
Animal b = new Cat();
b.setName("小花");
Animal c = new Bird();
c.setName("小飛");
//判斷大小compareTo
// System.out.println("");
// int result = a.compareTo(b);
// System.out.println("a.compareTo(b) = " + result);
// result=b.compareTo(c);
// System.out.println("b.compareTo(c) = "+result);
Set<Animal> set3 = new TreeSet<>();
set3.add(a);
set3.add(b);
set3.add(c);
System.out.println(set3);
/*
若要將動物也使用TreeSet會出現錯誤,因為動物無法排序
Dog cannot be cast to java.lang.Comparable
將 a 加入 TreeSet ,轉型失敗, a 所操作的 Dog 物件 無法轉成 java.lang.Comparable 型別
TreeSet 只接受具有 Comparable 特性的物件
所以要在Animal插入介面Comparable<Animal>,並且加入自定的規則
*/
/*
當加入Comparable<Animal>後,WHY小飛還是沒有出現
因為 b.compareTo(c) 的結果為 0,表示 b 與 c 相等,TreeSet 不重複的特性,所以 c(小飛) 不會放進 TreeSet 裡
( TreeSet 使用 compareTo() 判斷相等性 ,HashSet 使用 equals() 判斷相等性)
*/
顯示結果
為什麼 小飛 不在 TreeSet 裡 ?
因為 b.compareTo(c) 的結果為 0,表示 b 與 c 相等,TreeSet 不重複的特性,所以 c(小飛) 不會放進 TreeSet 裡
( TreeSet 使用 compareTo() 判斷相等性 ,HashSet 使用 equals() 判斷相等性)
最後整個 Animal 的關聯
code
Animal
TreeSetTest