java 比较器

两种方式

  • 自然排序:java.lang.Comparable
    Arrays.sort(T[]) 默认使用的比较方式。
  • 定制排序:java.util.Comparator
    Arrays.sort(T[], Comparator<? super T>)
  • 两种排序方式都是稳定的。并且,仅当比较方法返回正数时,才会触发元素的交换

Comparable

  • 代码实例
import java.util.Arrays;

public class Test02 {
    public static void main(String[] args) {
        Diamond[] diamonds = {new Diamond(3), new Diamond(-2), new Diamond(1), new Diamond(65), new Diamond(1)};
        System.out.println(Arrays.toString(diamonds));
        Arrays.sort(diamonds);
        System.out.println(Arrays.toString(diamonds));
    }

}

class Diamond implements Comparable<Diamond> {
    private Integer x;

    @Override
    public int compareTo(Diamond other) {
        return this.x - other.x;
    }

    @Override
    public String toString() {
        return "%d@%s".formatted(hashCode(), x.toString());
    }

    public Diamond(Integer x) {
        this.x = x;
    }
}
  • 运行结果
[124313277@3, 100555887@-2, 1769597131@1, 1983747920@65, 1543727556@1]
[100555887@-2, 1769597131@1, 1543727556@1, 124313277@3, 1983747920@65]

Comparator

  • 代码实例
import java.util.Arrays;
import java.util.Comparator;

public class Test02 {
    public static void main(String[] args) {
        Diamond[] diamonds = {new Diamond(3), new Diamond(-2), new Diamond(1), new Diamond(65), new Diamond(1)};
        System.out.println(Arrays.toString(diamonds));
//        Arrays.sort(diamonds, new Comparator<Diamond>() {
//            @Override
//            public int compare(Diamond o1, Diamond o2) {
//                return o2.getX() - o1.getX();
//            }
//        });
        Arrays.sort(diamonds, (o1, o2) -> o2.getX() - o1.getX());
        System.out.println(Arrays.toString(diamonds));
    }

}

class Diamond implements Comparable<Diamond> {
    private Integer x;

    @Override
    public int compareTo(Diamond other) {
        return this.x - other.x;
    }

    @Override
    public String toString() {
        return "%d@%s".formatted(hashCode(), x.toString());
    }

    public Diamond(Integer x) {
        this.x = x;
    }

    public Integer getX() {
        return x;
    }
}
  • 运行结果:定制化比较器 覆盖了 自然比较方式
[124313277@3, 611437735@-2, 100555887@1, 1769597131@65, 1983747920@1]
[1769597131@65, 124313277@3, 100555887@1, 1983747920@1, 611437735@-2]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值