TreeSet自定义对象遍历案例(自然排序)

第一部分:

//创建学生类
public class Student implements Comparable<Student> {
//成员变量
private String name;
private int age;
//构造方法
public Student(){
super();
}

public Student(String name, int age){
this.name = name;
this.age = age;
}
//成员方法
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;
}

@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}

@Override
public int compareTo(Student set) {
//按照年龄排序,主要条件(唯一性)
int num = this.age-set.age;
//年龄相同,但是姓名不同,不是同一个元素,所以判断姓名是否相同。
int num2 = num==0?this.name.compareTo(set.name):num;
return num2;

}
}

第二部分:
public class Tree {
public static void main(String[] args){
//创建集合
TreeSet<Student> set = new TreeSet<>();
//添加元素
Student s1 = new Student("容嬷嬷",55);
Student s2 = new Student("小燕子",45);
Student s3 = new Student("紫薇",50);
Student s4 = new Student("五阿哥",55);
Student s5 = new Student("尔康",60);
Student s6 = new Student("尔泰",58);
Student s7 = new Student("萧剑",55);
Student s8 = new Student("尔泰",58);
//把元素添加到集合中去
set.add(s1);
set.add(s2);
set.add(s3);
set.add(s4);
set.add(s5);
set.add(s6);
set.add(s7);
set.add(s8);

for (Student x:set){
System.out.println(x);
}
}
}


输出结果:

小燕子-----45
紫薇-----50
五阿哥-----55
容嬷嬷-----55
萧剑-----55
尔泰-----58
尔康-----60

猜你喜欢

转载自www.cnblogs.com/WTBK/p/9424821.html