自然排序: TreeSet调用集合元素的compareTo方法来比较元素的大小关系,然后将集合元素按照升序排列(从小到大,BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, Short 是按数字大小排序。Character 按字符的Unicode值的数字大小排序。String 按字符串中字符的Unicode值排序)。要求TreeSet集合中的元素实现Comparable接口。在compareTo方法中编写比较规则,在该方法中,比较当前对象(ths)和参数对象o(严格上说比较的是对象中的数据,比如按照对象的年龄排序)。
this>o:返回正整数1,this<o:返回负整数-1,this==0:返回0(此时认为两个对象为同一个对象)。
import java.util.Set;
import java.util.TreeSet;
class Person implements Comparable{
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
// public int compareTo(Person other) {
// if (this.age>other.age) {
// return 1;
// }else if(this.age<other.age){
// return -1;
// }
// return 0;
// }
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
return 0;
}
}
public class TreeSetDemo {
public static void main(String[] args) {
Set<Person> set = new TreeSet<>();
set.add(new Person("王大锤", 98));
set.add(new Person("李白", 36));
set.add(new Person("火星人", 18));
set.add(new Person("江小白", 9));
System.out.println(set);
}
}