Raf*_*orr 4 java arrays nested comparator ocpjp
我是 stackoverflow.com 的新手,但我经常在遇到问题时用它来搜索答案,但现在我找不到任何搜索我的问题的结果,所以我在这里问:) 我正在学习OCPJP SE 7 认证,考试 1Z0-804,我正在使用一本书(只有一个可用的 afaik,Ganesh\Sharma 的一个)在集合章节中,关于 Comparator 接口,这本书提供了使用两个 Comparator 的示例和 Comparable 接口对学生元素数组进行排序,但问题是关于比较器:
import java.util.*;
class Student implements Comparable<Student> {
private String id, name;
private Double cgpa;
public String getName() {
return name;
}
public String getId() {
return id;
}
public Double getCgpa() {
return cgpa;
}
public Student(String studentId, String studentName, double studentCGPA) {
id=studentId;
name=studentName;
cgpa=studentCGPA;
}
public String toString() {
return id+" "+name+" "+cgpa;
}
public int compareTo(Student that) {
return this.id.compareTo(that.id);
}
}
class StudentCGPA implements Comparator<Student> {
public int compare(Student s1, Student s2) {
return s1.getCgpa().compareTo(s2.getCgpa());
}
}
class MyMainClass {
public static void main(String[] args) {
Student[] students = { new Student("cs011", "Lennon", 3.1),
new Student("cs021", "McCartney", 3.4),
new Student("cs012", "Harrison", 2.7),
new Student("cs022", "Starr", 3.7),
};
Arrays.sort(students, new StudentCGPA());
System.out.println(Arrays.toString(students));
}
}
Run Code Online (Sandbox Code Playgroud)
所以它创建了一个新类,仅用于将 Comparator 接口与两个 Student 对象一起使用,但我认为这很不舒服所以我想知道:为什么我不能使用嵌套类(在 Student 中)?像这样:
import java.util.*;
class Student implements Comparable<Student> {
private String id, name;
private Double cgpa;
public String getName() {
return name;
}
public String getId() {
return id;
}
public Double getCgpa() {
return cgpa;
}
public Student(String studentId, String studentName, double studentCGPA) {
id=studentId;
name=studentName;
cgpa=studentCGPA;
}
public String toString() {
return id+" "+name+" "+cgpa;
}
public int compareTo(Student that) {
return this.id.compareTo(that.id);
}
static class StudentCGPA implements Comparator<Student> {
public int compare(Student s1, Student s2) {
return s1.getCgpa().compareTo(s2.getCgpa());
}
}
}
class MyMainClass {
public static void main(String[] args) {
Student[] students = { new Student("cs011", "Lennon", 3.1),
new Student("cs021", "McCartney", 3.4),
new Student("cs012", "Harrison", 2.7),
new Student("cs022", "Starr", 3.7),
};
Arrays.sort(students, new Student.StudentCGPA());
System.out.println(Arrays.toString(students));
}
}
Run Code Online (Sandbox Code Playgroud)
这本书没有提到使用嵌套类而不是普通类,但我不明白为什么这样做会很糟糕……我的代码(第二个)有什么问题吗?我是否应该遵循书中所说的,因为我对 Comparator 的实现是错误的?(注意:代码编译和运行没有问题,在两种情况下都具有预期的输出)
[cs012 Harrison 2.7, cs011 Lennon 3.1, cs021 McCartney 3.4, cs022 Starr 3.7]
Run Code Online (Sandbox Code Playgroud)
请帮助 :D 提前致谢。
如果您控制该类(并且它是一个类而不是接口),您可以将Comparatora实现为所比较对象的静态嵌套类。然而,根据目标类本身不支持的顺序(无论是通过存在还是通过提供类)来比较不受控制的类的实例,这种情况并不少见。在这种情况下,您必须创建自己的、单独的.ComparableComparatorComparator
即使你控制了一切,是否将Comparators实现为顶级类也是一个品味问题。我不知道你为什么称之为“不舒服”;我自己,我通常更喜欢尽可能避免嵌套类。还要注意,无论是否嵌套,Comparator实现类都将被编译为单独的类文件。