美文网首页
Java中TreeSet的三种比较规则

Java中TreeSet的三种比较规则

作者: 海人为记 | 来源:发表于2018-07-16 16:44 被阅读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;
    }
});

相关文章

  • Java中TreeSet的三种比较规则

    Java中TreeSet使用Comparator进行比较的三种方法 让元素具备比较性元素自身具备比较性,需要元素实...

  • Java的HashSet vs. TreeSet vs. Lin

    set是用来存储没有重复的元素的。set在java中有三种比较常用实现:HashSet, TreeSet and ...

  • TreeSet

    TreeSet如何比较自定义对象 Java中的TreeSet是Set的一个子类,TreeSet集合是用来对象元素进...

  • 20170705 Set类

    参考文献:《Java疯狂讲义》(第三版) Set类 三种实现类: 1、HashSet; 2、TreeSet; 3、...

  • java中treeset使用

    java中treeset使用 环境:jdk8 1:简介 这篇文章讲解java集合框架中实现set接口-TreeSe...

  • java集合中的TreeSet

    底层:树 红黑树/二叉树/平衡树 优缺点:维护数据的大小时是有序的;添加速度和删除速度高于ArrayList...

  • 深入了解TreeSet

    Java中的TreeSet是Set的一个子类,TreeSet集合是用来对象元素进行排序的,同样他也可以保证元素的唯...

  • java8中treeset源码分析

    大纲 treeset原理分析 treeset源码分析 1. treeset原理分析 treeset中的数据是唯一的...

  • 一起学习集合框架之 TreeSet

    什么是 TreeSet TreeSet 是一个具有唯一元素的二叉树的集合,又被翻译为 树集。Java 中的 Tre...

  • No. 4.2 TreeSet有序Set集合

    说TreeSet是有序集合,更通俗的解释应该是TreeSet提供了对存储元素的比较方法; TreeSet(Comp...

网友评论

      本文标题:Java中TreeSet的三种比较规则

      本文链接:https://www.haomeiwen.com/subject/sajbpftx.html