Collections.sort()使用比较器?

hak*_*a12 4 java collections comparator

import java.util.*;

public class C_2 {
    public static void main(String args[]) {
        String theStrings[] = { "x", "a", "b", "c", "d" };
        List l = Arrays.asList(theStrings);
        Collections.sort(l);                            // line a
        Collections.sort(l, new ThisIsMyThing());       // line b
        System.out.println(l);
    }
}

class ThisIsMyThing implements Comparator {
    public int compare(Object o1, Object o2) {
        String s1 = (String)o1;
        String s2 = (String)o2;

        return -1 * s1.compareTo(s2);
    }
}
Run Code Online (Sandbox Code Playgroud)

据我所知,该课程C_2基于两种不同的技术进行排序.一个是标准Collections.sort(l); 而另一个是Collections.sort(l,Comparator<>());我无法理解这种排序方法.有人可以向我解释一下吗?

Pau*_*tha 17

Collection.sort(l)假定的内容lComparable. Collection.sort(1, Comparator)使用自定义比较器来比较内容l,这就是你所做的.排序(包括sort()方法)的想法意味着对象必须是可比较的 - 在这种情况下,使用Comparable或者Comparator.

请注意,许多Java对象是已经媲美,其中包括String,DateNumber.对于那些,你可以使用Collection.sort(someList);

说你Circle上课了

public class Circle {
    double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    public double getArea(){
        return radius * radius * Math.PI;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您创建了100个Circle对象:

ArrayList<Circle> circleList = new ArrayList<>();

for (int i = 0; i < 100; i++) {
    // adds a circle with random radius
    circleList.add(new Circle((int)(Math.random() * 100)));
}

// try to sort the list
Collections.sort(circleList);   //compilation error: must be Comparable
Run Code Online (Sandbox Code Playgroud)

您无法对它们进行排序,因为Java不知道如何比较它们.你必须告诉Java:

public class Circle implements Comparable<Circle> {
    double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    // you MUST override the compareTo method from the Comparable interface
    @Override
    public int compareTo(Circle cirlce){
        if (this.getArea() > circle.getArea())
            return 1;
        else if (this.getArea() == circle.getArea())
            return 0;
        else 
            return -1;
    }

    public double getArea(){
        return radius * radius * Math.PI;
    }
}
Run Code Online (Sandbox Code Playgroud)

使用compareTo()Circle类中的方法,Java现在知道如何比较它们并可以对它们进行排序.

现在你可以这样做:

Collections.sort(circleList);
// Yayyy I'm being sorted by the size of my areas!!!!!
Run Code Online (Sandbox Code Playgroud)