Java中的自然排序和比较器排序

写在前面的话:刚开始学习着两者排序时我也是一头雾水,虽然能写出来但是稀里糊涂,几时该用哪个排序一点想法都没有,后来经过研究这两者的作用点不同,自然排序作用在实体类上,而比较器排序作用在装实体类的集合上。

1、自然排序:java.lang.Comparable 

Comparable 接口中只提供了一个方法: compareTo(Object obj) ,该方法的返回值是 int 。如果返回值为正数,则表示当前对象(调用该方法的对象)比 obj 对象“大”;反之“小”;如果为零的话,则表示两对象相等。

总结为一句话:实现Comparable,重写 compareTo方法

案列:以TreeMap为例,默认的升序,可以重写自然排序的方法改变原有排序

public static void testComparable(){
        TreeMap<Car,Object> tmp = new TreeMap<Car,Object>();
        tmp.put(new Car(4), "肆");
        tmp.put(new Car(1), "壹");
        tmp.put(new Car(5), "伍");
        tmp.put(new Car(3), "三");
        tmp.put(new Car(2), "贰");
        System.out.println(tmp);
        //结果://{Car [price=5.0]=伍, Car [price=4.0]=肆, Car [price=3.0]=三, Car [price=2.0]=贰, Car [price=1.0]=壹}
    }

//自定义TreeMap排序方法    自然排序   
class Car implements Comparable<Car>{
    private double price;
    
    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public Car(int price) {
        super();
        this.price = price;
    }


    @Override
    public int compareTo(Car o) {
        // TODO Auto-generated method stub
        if(this.price>o.getPrice()){
            return -1;//大的往前排
        }else if(this.price<o.getPrice()){
            return 1;//小的往后排
        }else{
            return 0;
        }
    }

    @Override
    public String toString() {
        return "Car [price=" + price + "]";
    }

2、比较器排序:java.util.Comparator 

总结为一句话:实现Comparator 接口,重写compare方法

public static void testComparator(){
        //HashMap<Integer,Object> hm = new HashMap<Integer,Object>();
        TreeMap<Integer,Object> tmp = new TreeMap<Integer,Object>(new MyComparatorBigtoSmall());
        tmp.put(4, "肆");
        tmp.put(1, "壹");
        tmp.put(5, "伍");
        tmp.put(3, "三");
        tmp.put(2, "贰");
        //System.out.println(tmp);//默认排序结果:{1=壹, 2=贰, 3=三, 4=肆, 5=伍}
        System.out.println(tmp);//修改为比较器排序(升序){5=伍, 4=肆, 3=三, 2=贰, 1=壹}
    }

//自定义TreeMap排序方法    比较器排序    
    class MyComparatorBigtoSmall implements Comparator<Integer>{

        @Override
        public int compare(Integer o1, Integer o2) {
            // TODO Auto-generated method stub
            return o2-o1;
        }

    }

如需了解两者的详细介绍,请点击https://blog.csdn.net/lichaohn/article/details/5389276​​​​​​​

猜你喜欢

转载自blog.csdn.net/Websphere_zxf/article/details/86418553