Nye*_*han 2 java sorting collections comparator data-structures
我的理解
如果返回值为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);
}
}
Run Code Online (Sandbox Code Playgroud)
如果是-1,那么这两个值会[交换]
不必要。这取决于排序代码使用哪两个元素调用您的回调。可能是返回-1不会让它交换它们,但返回1会。
我在没有返回值 1 的情况下测试了我的程序,并且排序正确。
您只是对正在排序的特定数据感到幸运,这发生在排序代码使用的特定算法不需要您的回调准确时。对于其他数据,它将无法正常工作,因为else if注释掉后,0当它们不相同时,您将返回(这两个相同),因为s1将在s2.
不要试图猜测文档告诉你什么,或者具体的实现是如何sort工作的。正确实现回调,使其返回负数、零或正数,具体取决于您应该如何订购两个元素。
| 归档时间: |
|
| 查看次数: |
103 次 |
| 最近记录: |