TreeSet集合存储自定义对象并遍历 如果对象的成员变量值相同即为同一个对象 按照年龄进行从大到小进行排序import java.util.Comparator; import java.util.TreeSet; /* TreeSet集合存储自定义对象并遍历 如果对象的成员变量值相同即为同一个对象 按照年龄进行从大到小进行排序 */ public class SetTest2 { public static void main(String[] args) { //1.无参构造,走的自然排序 // TreeSet<Student2> set1 = new TreeSet<>(); //2.带参数构造方法,走的是比较器排序 //匿名内部类实现 TreeSet<Student2> set1 = new TreeSet<>(new Comparator<Student2>() { @Override public int compare(Student2 o1, Student2 o2) { // return 0; //按照年龄进行从大到小进行排序 int i = o2.getAge() - o1.getAge(); //隐含条件 //年龄一样,姓名不一定一样 int i2 = i == 0 ? o1.getName().compareTo(o2.getName()) : i; return i2; } }); //创建学生对象 Student2 s1 = new Student2("刘备", 18); Student2 s2 = new Student2("曹操", 19); Student2 s3 = new Student2("孙权", 7); Student2 s4 = new Student2("诸葛亮", 11); Student2 s5 = new Student2("司马懿", 19); Student2 s6 = new Student2("刘备", 20); //将学生对象添加到集合中 set1.add(s1); set1.add(s2); set1.add(s3); set1.add(s4); set1.add(s5); set1.add(s6); //遍历 for (Student2 s : set1) { System.out.println(s.getName() + "---" + s.getAge()); } } }
import java.util.Objects; //无参构造--自然排序--向下转型---重写compareTo方法 public class Student2 implements Comparable<Student2>{ private String name; private int age; public Student2() { } public Student2(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 "Student1{" + "name='" + name + '\'' + ", age=" + age + '}'; } @Override public int compareTo(Student2 o) { //按照年龄进行从大到小排序 int i=o.age-this.age; //隐含条件 //年龄一样,姓名不一定一样 int i2=i==0?o.name.compareTo(this.name):i; return i2; } }
TreeSet集合存储自定义对象并遍历
最新推荐文章于 2025-05-27 23:57:37 发布