存储学生对象并遍历,创建TreeSet集合使用带参构造方法
要求:按照年龄从小大到排序,年龄相同时,按照姓名的字母顺序排序
结论:
1.用TreeSet集合存储自定义对象,带参构造方法使用的是比较器排序对元素进行排序
package com.itheima_90;
import java.util.Comparator;
import java.util.TreeSet;
/*
存储学生对象并遍历,创建TreeSet集合使用带参构造方法
要求:按照年龄从小大到排序,年龄相同时,按照姓名的字母顺序排序
*/
public class TreeSetDemo {
public static void main(String[] args) {
//创建集合对象
TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
//this.age - s.age
//s1,s2
int num = s1.getAge() - s2.getAge();
int num2 = num ==0?s1.getName().compareTo(s2.getName()):num;
return num2;
}
});
//创建学生对象
Student s1 = new Student("java",33);
Student s2 = new Student("hello",44);
Student s3 = new Student("world",55);
//添加元素
ts.add(s1);
ts.add(s2);
ts.add(s3);
//遍历
for(Student s:ts){
System.out.println(s.getName() + ":" + s.getAge());
}
}
}
package com.itheima_90;
public class Student {
private String name;
private int age;
public Student(){}
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;
}
}