Java进阶-自定义类型实现 Comparable 接口

放在 TreeSet 集合中的元素需要实现 java.lang.Comparable 接口,并且实现 compareTo 方法,equals 方法可以不写

  1. 在自定义类型继承 Comparable<自定义类型> 接口
  2. 快捷键 Alt+1,生成 compareTo 方法,开始写比较的规则
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.util.TreeSet;

public class TreeSetTest03 {

public static void main(String[] args) {
Customer c1 = new Customer(10);
Customer c2 = new Customer(15);
Customer c3 = new Customer(12);
Customer c4 = new Customer(10);

// 创建 TreeSet 集合
TreeSet<Customer> customers = new TreeSet<>();

// 添加元素
customers.add(c1);
customers.add(c2);
customers.add(c3);
customers.add(c4);

// 遍历
for (Customer c : customers) {
System.out.println(c);
// Customer [age=10]
// Customer [age=12]
// Customer [age=15]
}
}

}

class Customer implements Comparable<Customer> {
int age;

public Customer(int age) {
super();
this.age = age;
}

@Override
public String toString() {
return "Customer [age=" + age + "]";
}

// 需要在这个方法中编写比较的逻辑,或者说比较的规则,按照什么进行比较
// k.compareTo(t.key)
// 拿着参数 k 和集合中的每一个 k 进行比较,返回值可能是 >0 <0 =0
@Override
public int compareTo(Customer c) { // c1.compareTo(c2);
// this 是 c1
// c 是 c2
// c1 和 c2 比较的时候,就是 this 和 c 比较
return this.age - c.age;
}
}