TreeSet對非自然順序元素的排序


/*
1. 往TreeSet添加元素的時候,如果元素本身具備了自然順序的特性,那么就按照元素自然順序的特性進行排序存儲。

2. 往TreeSet添加元素的時候,如果元素本身不具備自然順序的特性,那么該元素所屬的類必須要實現Comparable接口,把元素
的比較規則定義在compareTo()方法上。

3. 如果比較元素的時候,compareTo方法返回的是0,那么該元素就被視為重復元素,不允許添加.
(注意:TreeSet與HashCode、equals方法是沒有任何關系。)

4. 往TreeSet添加元素的時候, 如果元素本身沒有具備自然順序 的特性,而元素所屬的類也沒有實現Comparable接口,
那么必須要在創建TreeSet的時候傳入一個比較器。

5. 往TreeSet添加元素的時候,如果元素本身不具備自然順序的特性,而元素所屬的類已經實現了Comparable接口,
在創建TreeSet對象的時候也傳入了比較器那么是以 比較器的比較規則優先 使用。

如何自定義定義比較器: 自定義一個類實現Comparator接口即可,把元素與元素之間的比較規則定義在compare方法內即可。
*/

 1 class Employee implements Comparable<Employee> {
 2     String name;
 3     int id;
 4     int salary;
 5 
 6     public Employee(String name, int id, int salary) {
 7         this.name = name;
 8         this.id = id;
 9         this.salary = salary;
10     }
11 
12     @Override
13     public String toString() {
14         return "{name=" + name + ", id=" + id + ", salary=" + salary + "}";
15     }
16 
17     @Override
18     public int compareTo(Employee e) { // 負整數、零或正整數,根據此對象是小於、等於還是大於指定對象。
19         return this.salary - e.salary;
20     }
21 }
22 
23 // 自定義一個比較器
24 class MyComparator implements Comparator<Employee> {
25     @Override
26     public int compare(Employee o1, Employee o2) {
27         return o1.id - o2.id;
28     }
29 }
30 
31 public class Demo6 {
32     public static void main(String[] args) {
33         // 用Comparable接口,此時比較salary
34         TreeSet tree = new TreeSet();
35         tree.add(new Employee("Jay", 1, 1000));
36         tree.add(new Employee("Lee", 4, 3000));
37         tree.add(new Employee("MJ", 2, 2000));
38         tree.add(new Employee("JK", 3, 500));
39 
40         System.out.println("用Comparable接口,此時比較salary");
41         Iterator it = tree.iterator();
42         while (it.hasNext()) {
43             System.out.println(it.next());
44         }
45 
46         System.out.println("*******************");
47 
48         // 用Comparator比較器,此時比較id
49         MyComparator comparator = new MyComparator();// 創建一個比較器對象
50         TreeSet tree2 = new TreeSet(comparator); // 創建TreeSet的時候傳入比較器
51         tree2.add(new Employee("Jay", 1, 1000));
52         tree2.add(new Employee("Lee", 4, 3000));
53         tree2.add(new Employee("MJ", 2, 2000));
54         tree2.add(new Employee("JK", 3, 500));
55 
56         System.out.println("用Comparator比較器,此時比較id");
57         Iterator it2 = tree2.iterator();
58         while (it2.hasNext()) {
59             System.out.println(it2.next());
60         }
61     }
62 
63 }

 

結果為:

用Comparable接口,此時比較salary
{name=JK, id=3, salary=500}
{name=Jay, id=1, salary=1000}
{name=MJ, id=2, salary=2000}
{name=Lee, id=4, salary=3000}
*******************
用Comparator比較器,此時比較id
{name=Jay, id=1, salary=1000}
{name=MJ, id=2, salary=2000}
{name=JK, id=3, salary=500}
{name=Lee, id=4, salary=3000}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM