指定排序规则的TreeSet集合

时间:2021-05-11 06:53:58

指定排序规则的TreeSet集合

import java.util.Set ;

import java.util.TreeSet ;
class Person implements Comparable<Person>{
private String name ;
private int age ;
public Person(String name,int age){
this.name = name ;
this.age = age ;
}
public String toString(){
return "姓名:" + this.name + ";年龄:" + this.age ;
}
public int compareTo(Person per){
if(this.age>per.age){
return 1 ;
}else if(this.age<per.age){
return -1 ;
}else{
return this.name.compareTo(per.name) ; // 调用String中的compareTo()方法
}
}
};
public class TreeSetDemo04{
public static void main(String args[]){
Set<Person> allSet = new TreeSet<Person>() ;
allSet.add(new Person("张三",30)) ;
allSet.add(new Person("李四",31)) ;
allSet.add(new Person("王五",32)) ;
allSet.add(new Person("王五",32)) ;
allSet.add(new Person("王五",32)) ;
allSet.add(new Person("赵六",33)) ;
allSet.add(new Person("孙七",33)) ;
System.out.println(allSet) ;
}

};

运行结果:
[姓名:张三;年龄:30, 姓名:李四;年龄:31, 姓名:王五;年龄:32, 姓名:孙七;年龄:33, 姓名:赵六;年龄:33]