package com.czie.iot1913.lps.itheima02;
import java.util.Comparator;
import java.util.TreeSet;
/**
* @author 1944900433@qq.com
* @date 2022-03-18 22:21
*/
public class TreeSetDemo01 {
public static void main(String[] args) {
//TreeSet(Collection<? extends E> c)
//构造一个新的树集包含在指定集合的元素,根据其元素的自然排序排序。
TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
int num=s1.getAge()-s2.getAge();
int num2=num==0? s1.getName().compareTo(s2.getName()):num;
return num2;
}
});
Student s1 = new Student("西施",21);
Student s2 = new Student("杨玉环",22);
Student s3 = new Student("貂蝉",20);
Student s4 = new Student("王昭君",19);
Student s5 = new Student("昭君",19);
Student s6 = new Student("昭君",19);
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
ts.add(s5);
ts.add(s6);
for (Student s:ts){
System.out.println(s.getName()+","+ s.getAge());
}
}
}
package com.czie.iot1913.lps.itheima02;
import java.util.Objects;
/**
* @author 1944900433@qq.com
* @date 2022-03-18 22:20
*/
public class Student {
private String name;
private int age;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Student student = (Student) o;
return age == student.age && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, 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;
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public Student() {
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix