java 什么决定了 Comparator / Comparable 集合类中的升序或降序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26107921/
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-11-02 09:18:45  来源:igfitidea点击:

What determines ascending or descending order in Comparator / Comparable collection class?

javasortingcollectionsinterfacecomparable

提问by David Prun

I understand we can sort or order the objects, stored in Collection as per our requirement(s).

我知道我们可以根据我们的要求对存储在 Collection 中的对象进行排序或排序。

While I get deep understanding, I am not convinced by the fact that ascending and descending order of arrangement is achieved by (a - b) ->ascending or (b - a) -> descending where "a" and "b" are class members we chose to compare.

虽然我得到了深刻的理解,但我不相信排列的升序和降序是通过 (a - b) -> 升序或 (b - a) -> 降序实现的,其中“a”和“b”是类我们选择比较的成员。

Example:

例子:

public int compareTo(Student s) {
     return this.grade - s.grade; //ascending order 
    // return s.grade - this.grade; // descending order
}

What is logic behind ordering object elements? how "(this.grade - s.grade)" if positive 1 moves "this.grade" front and puts "s.grade" next in order, why not other way around? Who validates the compare result (+1, -1, 0) and then puts in ascending order or descending order respectively, is there any documentation that describes internal working of this part?

排序对象元素背后的逻辑是什么?"(this.grade - s.grade)" 如果正 1 将 "this.grade" 移到前面并按顺序放置 "s.grade",为什么不反过来呢?谁验证比较结果(+1,-1,0),然后分别按升序或降序排列,有没有描述这部分内部工作的文档?

public class Student implements Comparable <Student>{
    String name;
    int grade;
    public Student(String name, int grade) {
        this.name = name;
        this.grade = grade;
    }
    public int compareTo(Student s) {
         return this.grade - s.grade; //ascending order 
        // return s.grade - this.grade; // descending order
    }
    public String toString() {
        return this.name + ", " + this.grade;
    }
}

Please share, thank you much!

求分享,万分感谢!



Edit:

编辑:

I get the Java docs, my question is this:

我得到了 Java 文档,我的问题是:

sort these grades (13, 2)

Case ascending -> return this.grade - s.grade;

picture in my mind: 
compare (13, 2) , (13 - 2) > 0 so move 2 to front.
result -> 2, 13
------
Case descending -> return s.grade - this.grade;

picture in my mind: 
compare (2, 13) , (2 - 13) < 0 so move 13 to front.

result -> 13, 2

"How does this happen?" was my original question. I read the docs, still couldn't figure out.

“这是怎么回事?” 是我原来的问题。我阅读了文档,仍然无法弄清楚。

采纳答案by dkatzel

What is logic behind ordering object elements? how "(this.grade - s.grade)" if positive 1 moves "this.grade" front and puts "s.grade" next in order, why not other way around?

排序对象元素背后的逻辑是什么?"(this.grade - s.grade)" 如果正 1 将 "this.grade" 移到前面并按顺序放置 "s.grade",为什么不反过来呢?

Using negative numbers to say "this is less than that", positive numbers to say "this is more than that" and 0 to say "these 2 things are equal" has been in many computer languages for 30+ years.

用负数表示“这小于那个”,用正数表示“这大于那个”,用 0 表示“这两件事相等”已经在许多计算机语言中使用了 30 多年。

Who validates the compare result (+1, -1, 0) and then puts in ascending order / descending order respectively, is there any documentation that describes internal working of this part?

谁验证比较结果(+1、-1、0)然后分别按升序/降序排列,有没有描述这部分内部工作的文档?

There are several internal classes that use the return value to reorder elements in arrays or collections including

有几个内部类使用返回值对数组或集合中的元素进行重新排序,包括

Collections.sort()Arrays.sort()TreeSet

Collections.sort()Arrays.sort()TreeSet

EDIT

编辑

To answer HOW that works you will have to look at the source code for each of the classes I listed above. Some of them are quite complicated to try to make the sorting as efficient as possible. But in general, it all boils down to code like this:

要回答它是如何工作的,您必须查看我上面列出的每个类的源代码。其中一些非常复杂,试图使排序尽可能高效。但总的来说,这一切都归结为这样的代码:

if( data[i].compareTo(data[j]) > 0 ){
   // swap data[i] and  data[j]
}

回答by Jay Modi

@DavidPrun Good question. I have tried explaining this with an example.

@DavidPrun 好问题。我试过用一个例子来解释这一点。

(x,y) -> (2, 5)

(x,y) -> (2, 5)

Ascending Order(x.compareTo(y)):

升序(x.compareTo(y)):

if x.compareTo(y) == 1, then x > y , since y is smaller than x, you would have to move y in front of x.

2.compareTo(5) == 1 , Then don't move 5 in front of 2.

Descending Order(y.compareTo(x)):

降序(y.compareTo(x)):

if y.compareTo(x) == 1, then y > x , since y is greater than x, you would have to move y in front of x.

5.compareTo(2) == -1 , Move 5 in front of 2.

Basically, we will always move y in front of x, if the result of compareTo method is 1.

基本上,如果 compareTo 方法的结果为 1,我们将始终将 y 移动到 x 之前。

回答by vlatkozelka

The Collections.sort() methods does .

Collections.sort() 方法确实如此。

now idk what exactly the algorithm of sort() in java is , i beleive its a modified double merged sort ... but somewhere in that code compareTo(Comparable c) is called to determin what is greater/lesser than , ill try to explain in a simplier algorithm :

现在我知道 java 中 sort() 的算法到底是什么,我相信它是一种修改后的双合并排序……但是在该代码中的某个地方调用 compareTo(Comparable c) 来确定大于/小于什么,我试着解释一下在一个更简单的算法中:

lets say i have Circle , usually u would compare circles by their diameter so ...

假设我有 Circle ,通常你会通过它们的直径来比较圆圈,所以......

public class Circle implements Comparable<Cricle> {
 int diameter;
 //constructor
 public int compareTo(Circle c){
  return this.diameter-c.diameter;
   }

now lets make an array of circles :

现在让我们制作一个圆圈数组:

ArrayList<Circle> collection = new ArrayList;
collection.add(new Circle(10)); // and more circles

now lets assume this is the sorting algorithm defined in Collection.sort() :

现在让我们假设这是 Collection.sort() 中定义的排序算法:

  Comparable tmp;
  for(int i=0;i<collection.size();i++){
   for(int j=i;j<collection.size();j++){
    if(collection.get(j).compareTo(collection.get(i)>0){
      //swap
      tmp=collection.get(i);
      collection.set(i,collection.get(j));
      collection.set(j,tmp);
     }
    }
   }

now im not sure i wrote the sorting algorithm write (asceding/descending) i just did it fast , but i guess the point is clear as of how sort() is deciding what goes where ... you can ask in comment for further explanaition

现在我不确定我写的排序算法写(升序/降序)我只是做得很快,但我想重点很清楚 sort() 如何决定什么去哪里......你可以在评论中询问进一步的解释