亲宝软件园·资讯

展开

Java Comparable与Comparator Java基础之Comparable与Comparator概述

小白划水 人气:0
想了解Java基础之Comparable与Comparator概述的相关内容吗,小白划水在本文为您仔细讲解Java Comparable与Comparator的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Java,Comparable与Comparator,java接口,下面大家一起来学习吧。

自然排序Comparable

在这里插入图片描述

对于自定义类进行排序要实现Comparable接口,重写compareTo() 方法,如果不重写,像使用Arrays.sort()排序就会报错

package com.che.lambda;

import java.util.Objects;

/**
 * @author cheyuhang on 2021/4/23
 */
public class Good  implements Comparable{
    private String name;
    private Double price;

    public Good(String name, Double price) {
        this.name = name;
        this.price = price;
    }

    public Good() {
    }

    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 boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Good good = (Good) o;
        return Objects.equals(name, good.name) && Objects.equals(price, good.price);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, price);
    }

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

    @Override
    public int compareTo(Object o) {
        if (o instanceof Good){          //判断传递参数是否属于商品
            Good good=(Good) o;
            if(this.price >good.price){
                return 1;
            }else if(this.price <good.price) {
                return -1;
            }else {
                return 0;
            }
        }
        throw  new RuntimeException("传入数据类型不一致");
    }
}

定制排序Comparator

使用场景:当类没有实现Comparable接口或者实现了Comparable接口,但不符合我期望的排序规则时进行使用

@Test
    public void test02() {
        Good[] arr=new Good[5];
        arr[0] =new Good("zhangsan",234.0);
        arr[1] =new Good("lisi",2343.0);
        arr[2] =new Good("wangwu",2354.0);
        arr[3] =new Good("zhaoliu",2334.0);
        arr[4] =new Good("tianqi",2347.0);
        System.out.println(Arrays.toString(arr));
        Arrays.sort(arr, new Comparator<Object>() 
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof Good && o2 instanceof Good){
                    Good g1=(Good) o1;
                    Good g2=(Good) o2;
                    return Double.compare(g1.getPrice(),g2.getPrice());
                    //return g1.compareTo(g2);
                }
                throw new RuntimeException("数据类型不一致");
            }
        });
        System.out.println(Arrays.toString(arr));
    }

加载全部内容

相关教程
猜你喜欢
用户评论