📜  使用Java Comparable 和 Comparator 对 Triplet 数组进行排序(1)

📅  最后修改于: 2023-12-03 15:22:18.695000             🧑  作者: Mango

使用Java Comparable和Comparator对Triplet数组进行排序

在Java中,我们可以使用ComparableComparator来对对象进行排序。Comparable接口是一个对象自身与其他对象进行比较的方法,而Comparator接口是一个独立的比较器,用于比较两个不相干的对象。

在本篇文章中,我们将介绍如何使用ComparableComparatorTriplet数组进行排序。

Triplet类的定义
public class Triplet implements Comparable<Triplet> {

    private int a;
    private int b;
    private int c;

    public Triplet(int a, int b, int c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public int getA() {
        return a;
    }

    public void setA(int a) {
        this.a = a;
    }

    public int getB() {
        return b;
    }

    public void setB(int b) {
        this.b = b;
    }

    public int getC() {
        return c;
    }

    public void setC(int c) {
        this.c = c;
    }

    @Override
    public int compareTo(Triplet o) {
        if (this.a != o.a) {
            return this.a - o.a;
        } else if (this.b != o.b) {
            return this.b - o.b;
        } else {
            return this.c - o.c;
        }
    }
}

Triplet类表示一个由三个整数组成的三元组,实现了Comparable接口以支持自己和其他对象的比较。重写compareTo方法根据abc的值来比较Triplet对象。

使用Comparable进行排序
public static void main(String[] args) {

    Triplet[] triplets = {new Triplet(3, 2, 1), new Triplet(1, 2, 3), new Triplet(2, 3, 1)};
    Arrays.sort(triplets);

    for (Triplet triplet : triplets) {
        System.out.println(triplet.getA() + " " + triplet.getB() + " " + triplet.getC());
    }
}

下面是输出结果:

1 2 3
2 3 1
3 2 1

使用Arrays.sort方法对Triplets数组进行排序,结果按abc的顺序排列。

使用Comparator进行排序
public static void main(String[] args) {

    Triplet[] triplets = {new Triplet(3, 2, 1), new Triplet(1, 2, 3), new Triplet(2, 3, 1)};
    Comparator<Triplet> comparator = new Comparator<Triplet>() {
        @Override
        public int compare(Triplet o1, Triplet o2) {
            if (o1.getC() != o2.getC()) {
                return o1.getC() - o2.getC();
            } else if (o1.getB() != o2.getB()) {
                return o1.getB() - o2.getB();
            } else {
                return o1.getA() - o2.getA();
            }
        }
    };
    Arrays.sort(triplets, comparator);

    for (Triplet triplet : triplets) {
        System.out.println(triplet.getA() + " " + triplet.getB() + " " + triplet.getC());
    }
}

下面是输出结果:

3 2 1
2 3 1
1 2 3

在上面的例子中,我们创建了一个Comparator匿名类对象并重写了compare方法,该方法指定了按cba的顺序进行排序。然后,我们使用该比较器对Triplets数组进行排序。

总结

使用ComparableComparator可以很容易地对对象进行排序。在本篇文章中,我们展示了如何使用ComparableComparatorTriplet数组进行排序。请注意,使用Comparable进行排序是对某个特定的类进行排序,而使用Comparator进行排序可能会对多个类进行排序。