package com.heima.bean;
public class Student implements Comparable<Student> {
private String name;
private int age;
public Student() {
super();
}
public Student(String name, int age) {
super();
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;
}
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public int compareTo(Student o) {
int num = this.age - o.age;
return num == 0 ? this.name.compareTo(o.getName()):num;
}
}
package com.heima.test;
import java.util.Comparator;
import java.util.TreeSet;
import com.heima.bean.Student;
public class Test10 {
/**
* * 10:编写一个Student类: 里面有 String name , int age 两个属性, TreeSet 保存5 个 学生对象, 要求:
* 1:自然顺序(Comparable) 实现 按照年龄 从大到小 排列
* 2:比较器顺序(Comparator) 实现 按照 名字的长度排列(可以重复,不考虑年龄)
* 3:验证两种比较 的优先级 ???????
*/
public static void main(String[] args) {
//* 1:自然顺序(Comparable) 实现 按照年龄 从大到小 排列
TreeSet<Student> ts1 = new TreeSet<>();//自然顺序排序,需要Person类实现Comparable接口并重写compareTo方法
ts1.add(new Student("张三",23));
ts1.add(new Student("李四",21));
ts1.add(new Student("王五",24));
ts1.add(new Student("赵六",20));
ts1.add(new Student("周七",22));
for (Student stu : ts1) {
System.out.println(stu);
}
System.out.println("-----------------------------------");
// * 2:比较器顺序(Comparator) 实现 按照 名字的长度排列(可以重复,不考虑年龄)
TreeSet<Student> ts2 = new TreeSet<>(new Comparator<Student>() {//比较器顺序(匿名内部类方式)
@Override
public int compare(Student s1, Student s2) {
int num = s1.getName().length() - s2.getName().length(); //姓名长度是主要判断条件
int num2 = num == 0 ? s1.getName().compareTo(s2.getName()): num;
return num2 == 0 ? s1.getAge()-s2.getAge():num2;
}
});
ts2.add(new Student("zhangsan",23));
ts2.add(new Student("lisi",21));
ts2.add(new Student("wangwu",24));
ts2.add(new Student("zhaoliu",20));
ts2.add(new Student("zhouqi",22));
for (Student stu : ts2) {
System.out.println(stu);
}
//ts2集合输出结果还是按照名字长度排序的,由此可以看出比较器顺序优先.
}
}
|