- 调用方法的对象和参数对象比较
- 如果返回0,代表两个对象相等。返回负数,代表调用方法的对象小,参数对象的大(升序)。
- 返回正数,代表调用方法的对象大,参数对象小(降序)。
- 理解不了,直接把规律记住就行了(点一下试一试)
@Override
public int compareTo(Student stu) {
int result = (int) Math.ceil(this.getScope() - stu.getScope());
result = result == 0 ? this.getAge().compareTo(stu.getAge()) : result;
result = result == 0 ? this.getName().compareTo(stu.getName()) : result;
System.out.println(this + "\t在和传入的对象\t" + stu + "比较" + "\t结果为:" + result);
System.out.println("========================");
return result;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", scope=" + scope +
", age=" + age +
'}';
}
public class TestOne {
public static void main(String[] args) {
TreeSet<Student> set = new TreeSet<>();
set.add(new Student("liusan",90.0,20));
set.add(new Student("lisi",90.0,20));
set.add(new Student("wangwu",99.0,22));
set.add(new Student("sunliu",100.0,22));
System.out.println("========================");
for (Student student : set) {
System.out.println(student);
}
}
}
Student{name='liusan', scope=90.0, age=20} 在和传入的对象 Student{name='liusan', scope=90.0, age=20}比较 结果为:0
========================
Student{name='lisi', scope=90.0, age=20} 在和传入的对象 Student{name='liusan', scope=90.0, age=20}比较 结果为:-2
========================
Student{name='wangwu', scope=99.0, age=22} 在和传入的对象 Student{name='liusan', scope=90.0, age=20}比较 结果为:9
========================
Student{name='sunliu', scope=100.0, age=22} 在和传入的对象 Student{name='liusan', scope=90.0, age=20}比较 结果为:10
========================
Student{name='sunliu', scope=100.0, age=22} 在和传入的对象 Student{name='wangwu', scope=99.0, age=22}比较 结果为:1
========================
========================
Student{name='lisi', scope=90.0, age=20}
Student{name='liusan', scope=90.0, age=20}
Student{name='wangwu', scope=99.0, age=22}
Student{name='sunliu', scope=100.0, age=22}
总结一波
想要升序就用this减去传入来的对象。this.getScope() - stu.getScope
想要降序就用传入来的对象减去this。stu.getScope() -this.getScope