Java 比较器Comparable和Compartor的使用

本文通过示例介绍如何在Java中实现Comparable接口及使用Comparator接口进行对象排序的方法。首先,通过自定义Customer类并实现Comparable接口,按ID和年龄进行排序;其次,创建ConsumInfo类,并使用Comparator接口来实现基于价格和UID的排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Comparable使用


    public static void main(String[] args) {
        demo d = new demo();
        Custumer c1 = d.new Custumer(1, 1, "1");
        Custumer c2 = d.new Custumer(4, 2, "2");
        Custumer c3 = d.new Custumer(2, 3, "3");
        Custumer c4 = d.new Custumer(2, 4, "4");
        Custumer c5 = d.new Custumer(5, 5, "5");
        List<Custumer> custumers = new ArrayList<demo.Custumer>();
        custumers.add(c1);
        custumers.add(c2);
        custumers.add(c3);
        custumers.add(c4);
        custumers.add(c5);


        for(Custumer custumer:custumers){
            System.out.print("    "+custumer.getName());
        }
        System.out.println("\n----------------------");
        Collections.sort(custumers);

        for(Custumer custumer:custumers){
            System.out.print("    "+custumer.getName());
        }
    }

    class Custumer implements Comparable<Custumer> {

        private int id;
        private int age;
        private String name;

        public Custumer(int id, int age, String name) {
            this.id = id;
            this.age = age;
            this.name = name;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public String getName() {
            return name;
        }

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

        public int compareTo(Custumer o) {
            // TODO Auto-generated method stub
            //根据id排序,如果相同根据age排序
            if (o.getId() > id) {
                return -1;
            } else if (o.getId() < id) {
                return 1;
            } else {
                if (o.getAge() > age) {
                    return -1;
                } else if (o.getAge() < age) {
                    return 1;
                } else {
                    return 0;
                }
            }
        }

    }

Compartor使用

package test;

import java.util.Comparator;
/**
 * 具体的比较类(比较器),实现Comparator接口
 * @author breeze
 *
 */
public class ComparatorConsunInfo implements Comparator<ConsumInfo> {
    /**
     * 顺序(从小到大):
     * if(price < o.price){
            return -1;
        }
        if(price > o.price){
            return 1;
        }
     * 倒序(从大到小):
     * if(price < o.price){
            return 1;
        }
        if(price > o.price){
            return -1;
        }
     */
    @Override
    public int compare(ConsumInfo o1, ConsumInfo o2) {
         //首先比较price,如果price相同,则比较uid
        if(o1.getPrice() > o2.getPrice()){
            return 1;
        }

        if(o1.getPrice() < o2.getPrice()){
            return -1;
        }

        if(o1.getPrice() == o2.getPrice()){
            if(o1.getUid() > o2.getUid()){
                return 1;
            }
            if(o1.getUid() < o2.getUid()){
                return -1;
            }
        }
        return 0;
    }

}


/**
 * 需要进行比较的类
 * @author breeze
 *
 */
public class ConsumInfo{
    private int uid;
    private String name;
    private double price;
    private Date datetime;

    public ConsumInfo() {
        // TODO Auto-generated constructor stub
    }

    public ConsumInfo(int uid,String name,double price,Date datetime){
        this.uid = uid;
        this.name = name;
        this.price = price;
        this.datetime = datetime;

    }

    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }

    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 Date getDatetime() {
        return datetime;
    }

    public void setDatetime(Date datetime) {
        this.datetime = datetime;
    }

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

}


//测试类
public class ConsumInfoTest {

    public static void main(String[] args) {

        ConsumInfo consumInfo1 = new ConsumInfo(100, "consumInfo1", 400.0,new Date());
        ConsumInfo consumInfo2 = new ConsumInfo(200, "consumInfo1", 200.0,new Date());
        ConsumInfo consumInfo3 = new ConsumInfo(300, "consumInfo1", 100.0,new Date());
        ConsumInfo consumInfo4 = new ConsumInfo(400, "consumInfo1", 700.0,new Date());
        ConsumInfo consumInfo5 = new ConsumInfo(500, "consumInfo1", 800.0,new Date());
        ConsumInfo consumInfo6 = new ConsumInfo(600, "consumInfo1", 300.0,new Date());
        ConsumInfo consumInfo7 = new ConsumInfo(700, "consumInfo1", 900.0,new Date());
        ConsumInfo consumInfo8 = new ConsumInfo(800, "consumInfo1", 400.0,new Date());

        List<ConsumInfo> list = new ArrayList<ConsumInfo>();
        list.add(consumInfo1);
        list.add(consumInfo2);
        list.add(consumInfo3);
        list.add(consumInfo4);
        list.add(consumInfo5);
        list.add(consumInfo6);
        list.add(consumInfo7);
        list.add(consumInfo8);

        System.out.println("排序前:");
        //排序前
        for(ConsumInfo consumInfo : list ){
            System.out.println(consumInfo);
        }
        ComparatorConsunInfo comparatorConsunInfo = new ComparatorConsunInfo();//比较器
        Collections.sort(list,comparatorConsunInfo);//排序
        System.out.println("排序后:");
        //排序后
        for(ConsumInfo consumInfo :list){
            System.out.println(consumInfo);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值