专注Java教育14年 全国咨询/投诉热线:444-1124-454
星辉LOGO图
始于2009,口口相传的Java黄埔军校
首页 学习攻略 Java中TreeSet的三种比较方法

Java中TreeSet的三种比较方法

更新时间:2019-09-01 09:00:00 来源:星辉 浏览3232次

 

今天星辉java培训机构小编为大家分享“Java中TreeSet的三种比较方法”,希望能够帮助到大家,下面就随小编一起看看Java中TreeSet的三种比较方法都是什么?


  1、让元素具备比较性


  元素自身具备比较性,需要元素实现Comparable接口,重写compareTo方法,也就是让元素自身具备比较性,这种方式叫做元素的自然排序也就做默认排序


// 第一种比较方法

public class Student implements Comparable{

//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;

    }   

}




  2、写一个类来实现Comparator接口


  当元素自身不具备比较性,或者自身具备的比较性不是所需要的。那么此时可以让容器自身具备。需要定义一个类实现接口Comparator,重写compare方法,并将该接口的子类实例对象作为参数传递给TreeMap集合的构造方法。


import java.util.Comparator;


// 第二种比较方法

public class ComparatorLean implements Comparator{


    @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;

    }

}

TreeSettreeSet = new TreeSet<>(new ComparatorLean());


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



  3、第三种为匿名内部类方法


TreeSettreeSet = new TreeSet(new Comparator() {

    @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培训机构小编介绍的“Java中TreeSet的三种比较方法”的内容,希望通过此文能够帮助到大家,如有疑问,请在线咨询,有专业老师随时为你服务。


相关免费视频教程推荐


java TreeSet特点视频教程下载: http://www.quanmin114.com/xiazai/2508.html


提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>