Java SE笔记: TreeSet实现Comparable接口的两种方式

推荐使用第二种方式,编写比较器可以使数据类的程序耦合度降低,同时比较器也可以重复利用!

第一种方式:

数据类实现Comparable接口,实现其中的compareTo方法
创建对象时,使用TreeSet的默认构造函数!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
SortedSet users = new TreeSet();
class User implements Comparable {
//String name;
int age;
User(int age){
this.age = age;
}
public String toString() {
return "User[age="+age+"]";
}
//实现java.lang.Comparable;接口中的compareTo方法
//该方法程序员负责实现,SUN提供的程序已经调用了该方法.
//需求:按照User的age排序
public int compareTo(Object o) {
//编写一个比较规则.
int age1 = this.age;
int age2 = ((User)o).age;
return age2-age1;
}
}

第二种方式:

单独编写一个实现Comparator接口的比较器,实现其中的compare方法
创建对象时,使用TreeSet的构造函数传入比较器!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
SortedSet products = new TreeSet(new Comparator());
class ProductComparator implements Comparator {
//需求:按照商品价格排序
public int compare(Object o1, Object o2) {
double price1 = ((Product)o1).price;
double price2 = ((Product)o2).price;
if(price1==price2) {
return 0;
}
else if(price1>price2) {
return 1;
}
else {
return -1;
}
}
}

文章目录
  1. 1. 第一种方式:
  2. 2. 第二种方式: