Java Collections.sort() 使用比较器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19682818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 19:22:41  来源:igfitidea点击:

Collections.sort() using comparator?

javacollectionscomparator

提问by hakuna12

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);
    }
}

I understand that class C_2does sorting based on two different techniques. One is the standard Collections.sort(l);And the other is Collections.sort(l,Comparator<>());I am not able to understand this sort method. Can someone please explain it to me?

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

采纳答案by Paul Samsotha

Collection.sort(l)assumes that the contents of lare Comparable. Collection.sort(1, Comparator)uses a custom comparator to compare the contents of l, this is what you did. The very idea of sorting (including the sort()method) implies the objects MUST be comparable - in this case, with either Comparableor Comparator.

Collection.sort(l)假设 的内容lComparableCollection.sort(1, Comparator)使用自定义比较器来比较 的内容l,这就是您所做的。排序的想法(包括sort()方法)意味着对象必须具有可比性 - 在这种情况下,使用ComparableComparator

Note that many Java objects are comparable already, including String, Dateand Number. For those, you can just use Collection.sort(someList);

请注意,许多 Java 对象已经具有可比性,包括StringDateNumber。对于那些,你可以使用Collection.sort(someList);

Example

例子

Say you have a Circleclass

说你有一Circle堂课

public class Circle {
    double radius;

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

    public double getArea(){
        return radius * radius * Math.PI;
    }
}

If you created 100 Circleobjects:

如果您创建了 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

You can't sort them because Java has no idea how to compare them. You have to tell this to Java:

您无法对它们进行排序,因为 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;
    }
}

With the compareTo()method in the Circle class, Java now knows how to compare them and can sort them.

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

Now you can do this:

现在你可以这样做:

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

回答by Shoaib Chikate

Collections.sort which takes comparator sorts the List based on the Comparator provided by you and other follows natural sorting order.That is if you want to follow any custom sorting order then use this method. And nothing much to explain in that.

Collections.sort 采用Comparator根据您提供的Comparator对List进行排序,其他遵循自然排序顺序。也就是说,如果您想遵循任何自定义排序顺序,请使用此方法。没有什么可以解释的。

Use this link for explaination.

使用此链接进行说明。

回答by shikjohari

Sorting a collection is done using the Collections.sort(Collection) to sort your values. This method is for those who implements Comparableinterface. This interface defines the method comparewhich performs pairwise comparison of the elements and returns -1 if the element is smaller then the compared element, 0 if it is equal and 1 if it is larger. A Common example is Integer class.

使用 Collections.sort(Collection) 对集合进行排序来对您的值进行排序。此方法适用于实现Comparable接口的人。该接口定义了compare对元素进行成对比较的方法,如果元素小于比较元素,则返回 -1,如果相等则返回 0,如果大于则返回 1。一个常见的例子是 Integer 类。

If what to sort differently you can define your own implementation based on the Comparatorinterface.This approach is that you then sort any object by any attribute or even a combination of attributes. For example if you have objects of type Person with an attribute income and dateOfBirth you could define different implementations of Comparator and sort the objects according to your needs.

如果要以不同的方式排序,您可以根据Comparator接口定义自己的实现。这种方法是您然后按任何属性甚至属性组合对任何对象进行排序。例如,如果你有一个 Person 类型的对象,它有一个属性 income 和 dateOfBirth,你可以定义 Comparator 的不同实现,并根据你的需要对对象进行排序。