JAVA Study Notes - Common Classes (4) - Java Comparator (Comparable and Comparator)

1. Description: Objects in Java, under normal circumstances, can only be compared: == or !=. Cannot use > or <.

    但是在开发场景中,我们需要对多个对象进行排序,
    言外之意,就需要比较对象的大小如何实现?﹖使用两个接口中的任何一个: Comparable 或 comparator

Second, the use of Comparable interface: natural sorting

1. Like String, wrapper classes, etc. implement the Comparable interface, rewrite the compareTo() method , and give a way to compare two objects
2. After rewriting the compareTo() method like String, wrapper classes, carry out from small to large Arrangement
(in particular, in addition to implementing the compareTo() method rewritten by the Comparable interface, the wrapper class
also has a compare(x, y) method defined by the wrapper class itself)

3. Rewrite the rule of compareTo(obj):
If the current object this is greater than The formal parameter object obj returns a positive integer,
if the current object this is less than the formal parameter object obj, returns a negative integer, and
if the current object this is equal to the formal parameter object obj, returns zero.
4. For custom classes, if sorting is required, we can make the custom class implement the Comparable interface, override the compareTo() method and
specify in the compareTo(obj) method

public class Goods implements Comparable{
    
    
    private String name;
    private double price;

    public Goods() {
    
    
    }

    public Goods(String name, double price) {
    
    
        this.name = name;
        this.price = price;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public double getPrice() {
    
    
        return price;
    }

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

    @Override
    public String toString() {
    
    
        return "Goods{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }

    //指明商品比较大小的方式:按照价格从低到高,再按照name从低到高
    @Override
    public int compareTo(Object o) {
    
    
        if (o instanceof Goods){
    
    
            Goods goods = (Goods) o;
            if (this.price>goods.price){
    
    
                return 1;
            }else if (this.price<goods.price){
    
    
                return -1;
            }else {
    
    
//                return 0;
                return this.name.compareTo(goods.name);
            }
        }
        throw new RuntimeException("输入的数据有误");
    }
}

3. Use of the Comparator interface: custom sorting
1. Background:
When the element type does not implement the java.Lang.Comparable interface and it is inconvenient to modify the code,
or the sorting rules that implement the java.Lang.comparable interface are not suitable for the current operation,
Then you can consider using Comparator objects to sort
2. Rewrite the compare(0bobject o1, object o2) method to compare the size of o1 and o2:
if the method returns a positive integer, it means that o1 is greater than o2;
if it returns e, it means equal;
return A negative integer, indicating that o1 is less than o2.

public class CompareTest {
    
    
    /*
自然排序 自定义的Goods类实现了Comparable接口,重写了comparTo()
    */
    @Test
    public void test_1(){
    
    
        Goods[] goods = new Goods[6];
        goods[0]= new Goods("lenovoMouse", 34);
        goods[1]= new Goods("dellMouse", 43);
        goods[2]=new Goods("microsoftMouse",65);
        goods[3]= new Goods("xiaomiMouse", 12);
        goods[4]= new Goods("huaweiMouse", 226);
        goods[5]= new Goods("huaweiMouse", 65);

        Arrays.sort(goods);
        System.out.println(Arrays.toString(goods));
    }
    /*
    Comparator接口的使用:定制排序
    1.背景:
    当元素的类型没有实现java.Lang. Comparable接口朋又不方便修改代码,
    或者实现了java.Lang.comparable接口的排序规则不适合当前的操作,
    那么可以考虑使用Comparator 的对象来排序
    2.重写compare(Object o1,object o2)方法,比较o1和o2的大小:
    如果方法返回正整数,则表示o1大于o2 ;
    如果返回e,表示相等;
    返回负整数,表示o1小于o2。
    */
    @Test
    public void test2(){
    
    
        String[] arr = new String[]{
    
    "AA", "CC", "KK", "MM" , "GG" ,"JJ" , "DD"};
        //从大到小,默认是从小到大
        Arrays.sort(arr, new Comparator<String>() {
    
    
            @Override
            public int compare(String o1, String o2) {
    
    
                return -o1.compareTo(o2);
            }
        });
        System.out.println(Arrays.toString(arr));
    }
    @Test
    public void test3(){
    
    
        Goods[] goods = new Goods[6];
        goods[0]= new Goods("lenovoMouse", 34);
        goods[1]= new Goods("dellMouse", 43);
        goods[2]=new Goods("microsoftMouse",65);
        goods[3]= new Goods("xiaomiMouse", 12);
        goods[4]= new Goods("huaweiMouse", 226);
        goods[5]= new Goods("huaweiMouse", 65);

        Arrays.sort(goods, new Comparator<Goods>() {
    
    
            //指明商品比较大小的方式:按照产品名称从低到高排序,再按照价格从高到低排序
            @Override
            public int compare(Goods o1, Goods o2) {
    
    
                if (o1.getName().equals(o2.getName())) {
    
    
                    return -Double.compare(o1.getPrice(),o2.getPrice());
                }else {
    
    
                    return o1.getName().compareTo(o2.getName());
                }
            }
        });
        System.out.println(Arrays.toString(goods));
    }
}

Guess you like

Origin blog.csdn.net/m0_46450708/article/details/119617735