TreeSet集合排序方式一:自然排序Comparable

时间:2023-03-10 06:59:23
TreeSet集合排序方式一:自然排序Comparable

TreeSet集合默认会进行排序。因此必须有排序,如果没有就会报类型转换异常。

自然排序

Person class—>实现Comparable,实现compareTo()方法

package Homework1and2;

import java.text.CollationKey;
import java.text.Collator; /**
* Person类 有属性 name,age,sex
排序规则: 第一条件 年龄降序,第二条件 姓名 降序,第三条件 性别升序
* @author Administrator
*
*/
public class Person implements Comparable<Person> {
private static String name;
private int age;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", sex=" + sex + "]";
}
public Person(String name, int age, String sex) {
super();
this.name = name;
this.age = age;
this.sex = sex;
}
public Person() {
super();
}
//排序规则: 第一条件 年龄降序,第二条件 姓名 降序,第三条件 性别升序
@Override
public int compareTo(Person o) {
if(age>o.age){
return -1;
}else if(age<o.age){
return 1;
}else {
CollationKey key1=Collator.getInstance().getCollationKey(name);
CollationKey key2=Collator.getInstance().getCollationKey(o.name);
int num=key1.compareTo(key2);
if(num>0){
return -1;
}else if(num<0){
return 1;
}else {
CollationKey key3=Collator.getInstance().getCollationKey(sex);
CollationKey key4=Collator.getInstance().getCollationKey(o.sex);
int s=key3.compareTo(key4);
if(s>0){
return 1;
}else if(s<0){
return -1;
}else {
return 0;
}
} } } }

测试

public class Test1 {
public static void main(String[] args){
TreeSet<Person> list=new TreeSet<>();
//年龄降序
list.add(new Person("李白1", 15, "男"));
list.add(new Person("李白2", 18, "男"));
//姓名降序
list.add(new Person("a妲己3", 20, "女"));
list.add(new Person("z褒姒4", 20, "女"));
//性别升序
list.add(new Person("妲己", 17, "a女"));
list.add(new Person("妲己", 17, "z男"));
System.out.println(list); }
}