1.实现接口Comparable
实现顾客类,实例变量age,重写toString和comparaTo方法。
class Customer implements Comparable<Customer> {
int age;
public Customer(int age){
this.age = age;
}
@Override
public String toString() {
return "Customer[" +
"age=" + age +
']';
}
@Override
public int compareTo(Customer o) {
return this.age - o.age;
}
}
实现main方法
public static void main(String[] args) {
Customer c1 = new Customer(11);
Customer c2 = new Customer(22);
Customer c3 = new Customer(5);
TreeSet<Customer> customers = new TreeSet<>();
customers.add(c1);
customers.add(c2);
customers.add(c3);
for (Customer c:customers
) {
System.out.println(c);
}
}
2.实现构造器Comparator接口
2.1创建WuGui类和实现构造器
class WuGui{
int age;
public WuGui(int age){
this.age = age;
}
@Override
public String toString() {
return "小乌龟[" +
"age=" + age +
']';
}
}
class WuGuiComparator implements Comparator<WuGui>{
@Override
public int compare(WuGui o1, WuGui o2) {
return o1.age - o2.age;
}
}
实现main方法
public static void main(String[] args) {
TreeSet<WuGui> wuGuis = new TreeSet<>(new WuGuiComparator());
wuGuis.add(new WuGui(100));
wuGuis.add(new WuGui(5));
wuGuis.add(new WuGui(50));
wuGuis.add(new WuGui(77));
wuGuis.add(new WuGui(27));
for (WuGui wugui:wuGuis
) {
System.out.println(wugui);
}
}
2.2可以不创建类来实现Comparator接口,采用匿名内部类的方法。
TreeSet<WuGui> wuGuis = new TreeSet<>(new Comparator<WuGui>() {
@Override
public int compare(WuGui o1, WuGui o2) {
return o1.age-o2.age;
}
});