1.通过构造方法TreeSet(Comparator<? super E> comparator)指定比较器进行排序:
1.1.构造装入 TreeSet 的 bean
public class Foo {
private int num;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String toString() {
return "foo:" + this.getNum() + ",";
}
}
1.2.实现自己的比较器
public class MyComparator implements Comparator<Foo> {
public int compare(Foo f1, Foo f2) {
if (f1.getNum() > f2.getNum()) {
return 1;
} else if (f1.getNum() == f2.getNum()) {
return 0;
} else {
return -1;
}
}
}
1.3.new TreeSet时指定比较器
TreeSet<Foo> set = new TreeSet(new MyComparator());
至此:就可以实现 TreeSet 的排序功能了。
2.通过对需要添加到 TreeSet 的【元素】实现比较器接口进行排序。
2.1.对要添加到 TreeSet 中的元素实现 Comparable 接口
public class Foo implements Comparable {
private int num;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String toString() {
return "foo:" + this.getNum() + ",";
}
public int compareTo(Object obj) {
if (obj instanceof Foo) {
Foo foo = (Foo) obj;
if (this.num > foo.getNum()) {
return 1;
} else if (this.num == foo.getNum()) {
return 0;
} else {
return -1;
}
}
return 0;
}
}
2.2.创建 TreeSet 直接使用构造方法。
TreeSet<Foo> set = new TreeSet();
至此:就可以实现 TreeSet 的排序功能了。