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}
原文地址:https://www.cnblogs.com/shadowdoor/p/6816189.html