package com.javase.collection.set.treeset;
import java.util.TreeSet;
/**
*对于自定义类型来说,TreeSet可以排序吗?
* 答:能!但是 对于自定义类型需要实现Comparable接口,再实现compareTo()方法,这样就可以不重写equals()方法了。
*/
public class TreeSetText02 {
public static void main(String[] args) {
Person p1 = new Person(60);
Person p2 = new Person(30);
Person p3 = new Person(80);
Person p4 = new Person(50);
// 创建集合
TreeSet<Person> treeSet = new TreeSet<>();
// 添加元素
treeSet.add(p1);
treeSet.add(p2);
treeSet.add(p3);
treeSet.add(p4);
// 遍历集合
for (Person ele : treeSet) {
System.out.println(ele);
}
}
}
/*
输出结果:
Person[age=30]
Person[age=50]
Person[age=60]
Person[age=80]
*/
package com.javase.collection.set.treeset;
public class Person implements Comparable<Person> {
private int age;
public Person() {
}
public Person(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
'}';
}
@Override
public int compareTo(Person o) {
return this.age - o.age;//从小到大的顺序排序,反过来写:o.age - this.age,则变成从大到小排序。
}
}