Java中TreeSet的三种比较规则

2018-07-16  本文已影响17人  海人为记

Java中TreeSet使用Comparator进行比较的三种方法

  1. 让元素具备比较性
    元素自身具备比较性,需要元素实现Comparable接口,重写compareTo方法,也就是让元素自身具备比较性,这种方式叫做元素的自然排序也就做默认排序
// 第一种比较方法
public class Student implements Comparable<Student> {
//public class Student{
    
    private String name;
    private int age;
    @Override
    public int compareTo(Object o) {
                if(!(o instanceof Student))
                        throw new RuntimeException("不是学生对象");
                Student s = (Student) o;
                int differenceValue = this.age - s.age;
                if(differenceValue == 0) return this.name.compareTo(s.name);
        return differenceValue;
    }   
}
  1. 写一个类来实现Comparator接口
    当元素自身不具备比较性,或者自身具备的比较性不是所需要的。那么此时可以让容器自身具备。需要定义一个类实现接口Comparator,重写compare方法,并将该接口的子类实例对象作为参数传递给TreeMap集合的构造方法。
import java.util.Comparator;

// 第二种比较方法
public class ComparatorLean implements Comparator<Student> {

    @Override
    public int compare(Object o1, Object o2) {
                Student s1 = (Student) o1;
                Student s2 = (Student) o2;
                int differenceValue = this.age - s.age;
                if(differenceValue == 0) return new Integer(s1.getName().compareTo(s2.getName()));
        return differenceValue;
    }
}
TreeSet<Student> treeSet = new TreeSet<>(new ComparatorLean());

注意:当Comparable比较方式和Comparator比较方式同时存在时,以Comparator的比较方式为主;在重写compareTo或者compare方法时,必须要明确比较的主要条件相等时要比较次要条件,

  1. 第三种为匿名内部类方法
TreeSet<Student> treeSet = new TreeSet<Student>(new Comparator<Object>() {
    @Override
    public int compare(Object o1, Object o2) {
        Student s1 = (Student) o1;
        Student s2 = (Student) o2;
        int num = s1.getAge() - s2.getAge();
        if(num==0) return s1.getAge() - s2.getAge();
        return num;
    }
});
上一篇 下一篇

猜你喜欢

热点阅读