java比较器 --- 自定义类实现Comparable自然排序

自定义类实现Comparable自然排序

package com.ran;

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

    @Override
    public String toString() {
        return "Goods{" +
                "name='" + name + '\'' +
                ", 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;
    }

    public Goods() {
    }

    public Goods(String name, double price) {
        this.name = name;
        this.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 {
                //价格如果一样 名字是String类型就直接调用比较
                return -this.name.compareTo(goods.name);
            }
            //方式二
//           return Double.compare(this.price,goods.price);
        }

        throw new RuntimeException("传入的数据类型不一致");
    }
}
package com.ran;

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

    @Override
    public String toString() {
        return "Goods{" +
                "name='" + name + '\'' +
                ", 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;
    }

    public Goods() {
    }

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


    @Override
    public int compareTo(Object o) {
        if(o instanceof Goods){
            Goods goods=(Goods) o;
            if(goods.name==this.name){
                return Double.compare(this.getPrice(),goods.getPrice());
            }else {
                return this.name.compareTo(goods.getName());
            }
        }
        throw new RuntimeException("cuo");
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值