Java排序Comparable和Comparator

public class ComparableTest {

    public static void main(String[] args) {

        String[] arr = new String[] {"TT", "CC", "YY", "AA", "aa", "zz", "ii"};
        Arrays.sort(arr);
        // 默认排序
        System.out.println(Arrays.toString(arr));  // [AA, CC, TT, YY, aa, ii, zz]

        // 自然排序方法,实现Comparable接口的compareTo方法
        Product[] products = new Product[5];
        products[0] = new Product("C产品一", 6999);
        products[1] = new Product("D产品二", 4999);
        products[2] = new Product("A产品三", 5999);
        products[3] = new Product("R产品四",9999);
        products[4] = new Product("T产品五", 6199);

        Arrays.sort(products);
        System.out.println(Arrays.toString(products));
        // [Product [name=产品二, price=4999], 
        // Product [name=产品三, price=5999], 
        // Product [name=产品五, price=6199], 
        // Product [name=产品一, price=6999], 
        // Product [name=产品四, price=9999]]

        // 定制排序Comparator
        Comparator<Product> comparator = new Comparator<Product>() {
            @Override
            public int compare(Product o1, Product o2) {
                return o1.getName().compareTo(o2.getName());
            };
        };

        Arrays.sort(products, comparator);
        System.out.println(Arrays.toString(products));
        // [Product [name=A产品三, price=5999], 
        // Product [name=C产品一, price=6999], 
        // Product [name=D产品二, price=4999], 
        // Product [name=R产品四, price=9999], 
        // Product [name=T产品五, price=6199]]

    }

}

class Product implements Comparable<Object> {
    private String name;
    private int price;

    public Product() {
    }

    public Product(String name, int price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

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

    public int getPrice() {
        return price;
    }

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

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

    // @Override
    // public int compareTo(Product o) {
    //     return o.price - this.price;  // 从大到小
    // }

    @Override
    public int compareTo(Object o) {
        if (o == this) {
            return 0;
        }
        if (o instanceof Product) {
            Product p = (Product) o;
            return this.price - p.price;       // 从小到大    
        }
        throw new RuntimeException("类型不匹配");
    }

    

    

    
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值