
public interface Comparable<T>
compareTo方法被称为其自然比较方法 。注意让类实现该接口,注意泛型
String类重写了compareTo方法 所以可以直接调用
注意重写方法时规则的运用。
this代表s2 s代表s1
测试类
package com.Test01;
import java.util.TreeSet;
public class TreeSetDemo02 {
public static void main(String[] args) {
TreeSet<Student> ts = new TreeSet<Student>();
Student s1 = new Student("xishi", 29);
Student s2 = new Student("diaochan", 29);
Student s3 = new Student("yangyuhuan", 21);
Student s4 = new Student("wangzhaojun", 26);
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
for (Student s : ts) {
System.out.println(s.getName() + "," + s.getAge());
}
}
}
Student类
package com.Test01;
import java.util.Objects;
import java.util.TreeSet;
public class Student implements Comparable<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;
}
@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);
}
@Override
public int compareTo(Student s) {
int num = this.age - s.age;
int num2 = num == 0 ? this.name.compareTo(s.name) : num;
return num2;
}
}
原文:https://www.cnblogs.com/lsswudi/p/11408886.html