根据元素类实现了Comparable接口之后重写了compareTo方法的返回值是正数、负数、0三种值来排序:
如果是正数就代表非重复元素,升序添加到集合,如果将返回值设置为常数 1,就会按照添加顺序,可重复的添加到集合中;
如果是 0 就代表 重复元素,不会添加到集合,如果将返回值设置为常数 0,只会添加第一个元素;
如果是负数就代表非重复元素,降序添加到集合,如果将返回值设置为常数-1,就会按照添加逆序,可重复的添加到集合中。
public int compareTo(Student student) {
int num;
//首要条件 根据年龄升序排列
num = this.age - student.age;
//次要条件 根据姓名升序排列
int condition = num == 0 ? this.name.compareTo(student.name):num;
return condition;
}
}
/**
* this 就是 当前的元素, student是集合里要比较的元素
*/
Eg:
import java.util.Iterator;
import java.util.TreeSet;
public class Student implements Comparable<Student> {
private int age;
private String name;
public Student(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Student student = (Student) o;
if (age != student.age) {
return false;
}
return name.equals(student.name);
}
@Override
public String toString() {
return "Student{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
@Override
public int hashCode() {
int result = age;
result = 31 * result + name.hashCode();
return result;
}
public int compareTo(Student student) {
int num;
//首要条件 根据年龄升序排列
num = this.age - student.age;
//次要条件 根据姓名升序排列
int condition = num == 0 ? this.name.compareTo(student.name):num;
return condition;
}
}
class Test {
public static void main(String[] args) {
TreeSet<Student> set = new TreeSet<Student>();
set.add(new Student(16,"小芳"));
set.add(new Student(16,"小芳"));
set.add(new Student(18,"小微"));
Iterator<Student> iterator = set.iterator();
while(iterator.hasNext()){
Student next = iterator.next();
System.out.println("next = " + next);
}
}
}