Java---java比较器

package java0;

import org.junit.Test;

import java.awt.image.AreaAveragingScaleFilter;
import java.util.Arrays;
import java.util.Comparator;

/**
 *
 *
 * @create 2022-03-23 12:54
 */
public class CompareTest {
    @Test
    public void test2(){
        Goods[] arr=new Goods[5];
        arr[0]=new Goods("lenovoMouse",34);
        arr[1] = new Goods("dellMouse",43);
        arr[2] = new Goods("xiaomiMouse",12);
        arr[3] = new Goods("huaweiMouse",65);
        arr[4] = new Goods("microsoftMouse",43);

        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));


    }

    @Test
    public void test3(){
        String[] arr=new String[]{"AA","CC","KK","MM","GG","JJ","DD"};
        Arrays.sort(arr, new Comparator(){
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof String&&o2 instanceof String){
                    String s1=(String)o1;
                    String s2=(String)o2;
                    return -s1.compareTo(s2);
                }

                throw new RuntimeException("输入的数据类型不一致");
            }
        });
        System.out.println(Arrays.toString(arr));
    }
}
package java0;

/**
 *
 *
 * @create 2022-03-23 12:50
 */
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 +
                '}';
    }

    @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;
            }
        }
        throw new RuntimeException("输入的类型不对!");
    }
}
posted @ 2022-03-23 15:52  ice--cream  阅读(21)  评论(0编辑  收藏  举报