[英]What does return value -1, 0, 1 means exactly in Java collection sort with Comparator interface compare method?
我的理解
如果返回值为 0,则无事可做。 如果是-1,那么这两个值将被扫描。 如果我们想改变顺序(asc/desc),只需改变比较运算符。
我在网站上找到的
返回值将是 -1、0 或 1,因为第一个参数小于、等于或大于第二个参数。
我想知道的
为什么我们需要返回值 1? 我在没有返回值 1 的情况下测试了我的程序,并且它排序正确。
以下程序按年级升序对学生对象进行排序。 如果要更改排序顺序,请更改比较运算符。
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
Student s1 = new Student("JJJ", 5);
Student s2 = new Student("DDD", 2);
Student s3 = new Student("RRR", 4);
Student s4 = new Student("CCC", 4);
Student s5 = new Student("GGG", 3);
Student s6 = new Student("JJJ", 1);
List < Student > ls = new ArrayList < > ();
ls.add(s1);
ls.add(s2);
ls.add(s3);
ls.add(s4);
ls.add(s5);
ls.add(s6);
for (Student s: ls) {
s.print();
}
System.out.println("=====================");
ls.sort(new Comparator < Student > () {
@Override
public int compare(Student s1, Student s2) {
if (s1.grade < s2.grade) return -1;
// else if (s1.grade > s2.grade) return 1;
else return 0;
}
});
for (Student s: ls) {
s.print();
}
}
public static void printLs(List < Student > ls) {
for (Student s: ls) {
s.print();
}
}
}
class Student {
String name;
int grade;
Student(String name, int grade) {
this.name = name;
this.grade = grade;
}
void print() {
System.out.println(this.name + " - " + this.grade);
}
}
如果是-1,那么这两个值将[交换]
不必要。 这取决于排序代码调用回调的两个元素。 可能返回-1
不会使其交换它们,但返回1
会。
我在没有返回值 1 的情况下测试了我的程序,并且它排序正确。
您刚刚对您正在排序的特定数据感到幸运,这发生在排序代码使用的特定算法不需要您的回调是准确的。 对于其他数据,它将无法正常工作,因为else if
,当它们不相同时,您将返回0
(这两个相同),因为s1
将在s2
之后。
不要试图猜测文档告诉你什么,或者sort
的具体实现是如何工作的。 正确实现回调,使其返回负数、零或正数,具体取决于应如何对给定的两个元素进行排序。
我已经修改了您的代码以在开始时生成更多数据,以证明您的数据集太小而无法显示问题。
您可以在Coding Ground上查看并运行它。 (我不隶属)
不要依赖抽象的排序调用来始终使用相同的排序实现。 它可以根据数据集的大小调用不同的策略。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.