首页 课程 师资 教程 报名

Java中TreeSet的三种比较方法

  • 2019-09-01 09:00:00
  • 3181次 动力节点

 

今天动力节点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.bjpowernode.com/xiazai/2508.html


选你想看

你适合学Java吗?4大专业测评方法

代码逻辑 吸收能力 技术学习能力 综合素质

先测评确定适合在学习

在线申请免费测试名额
价值1998元实验班免费学
姓名
手机
提交