java TreeSet的排序之定制排序

TreeSet的自然排序是根据元素的大小进行升序排序的,若想自己定制排序,比如降序排序,就可以使用Comparator接口了:

该接口包含int compare(Object o1,Object o2)方法,用于比较两个对象的大小,比较结果和compareTo方法一致;

要实现定制排序,需要在创建TreeSet集合对象时,提供一个一个Comparator对象,该对象里负责集合元素的排序逻辑;

TreeSet(Comparator comparator)

Eg:

package july7;

//定制排序的话,必须在创建TreeSet集合对象的时候提供一个Comparator方法

import java.util.Comparator;

import java.util.Set;

import java.util.TreeSet;

class Student1{

    private Integer age;

   

    public Student1(Integer age) {

        super();

        this.age = age;

    }

    public Integer getAge() {

        return age;

    }

    public void setAge(Integer age) {

        this.age = age;

    }

    @Override

    public String toString() {

        return age + "";

    }

}

class MyComparator implements Comparator{

   

    @Override

    public int compare(Object o1, Object o2) {

        if(o1 instanceof Student1 & o2 instanceof Student1){

            Student1 s1 = (Student1)o1;

            Student1 s2 = (Student1)o2;

            if(s1.getAge() > s2.getAge()){

                return -1;

            }else if(s1.getAge() < s2.getAge()){

                return 1;

            }

        }

        return 0;

    }

}

public class Demo15 {

    public static void main(String[] args) {

        Set<Student1> s = new TreeSet(new MyComparator());

        /**

         * 要实现定制排序,需要在创建TreeSet集合对象时,提供一个一个Comparator对象,

         * 该对象里负责集合元素的排序逻辑;

         */

        s.add(new Student1(140));

        s.add(new Student1(15));

        s.add(new Student1(11));

        s.add(new Student1(63));

        s.add(new Student1(96));

       

        System.out.println(s);

    }

}

猜你喜欢

转载自www.cnblogs.com/fanweisheng/p/11136146.html
今日推荐