【发布时间】:2020-03-26 17:07:07
【问题描述】:
我正在上我的第二个计算机编程课程,并被要求编写一个实现 2 个比较器类的程序。下面是我的代码,但我不知道为什么 Collections.sort(newStudent, new sortByName());和 Collections.sort(newStudent, new sortByRollNo());引发错误。谢谢!
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class StudentObjects {
int rollno;
String name;
String address;
public StudentObjects(int rollno, String name, String address) { //constructor
this.rollno = rollno;
this.name = name;
this.address = address;
}
@Override
public String toString() {
return this.rollno + " " + this.name + " " + this.address; //to print in main
}
class sortByName implements Comparator<StudentObjects> {
public int compare(StudentObjects a, StudentObjects b) {
return a.name.compareTo(b.name);
}
}
class sortByRollNo implements Comparator<StudentObjects> {
public int compare(StudentObjects a, StudentObjects b) {
return a.rollno - b.rollno;
}
}
public static void main(String[] args) {
int i = 0;
ArrayList<StudentObjects> newStudent = new ArrayList<StudentObjects>();
newStudent.add(new StudentObjects(342, "Harry Potter", "4 Privet Drive"));
newStudent.add(new StudentObjects(555, "Hermione Granger", "67 Hampstead Garden"));
newStudent.add(new StudentObjects(788, "Ron Weasley", "5 Ottery St Catchpole"));
newStudent.add(new StudentObjects(542, "Albus Dumbledore", "88 Godric's Hollow"));
newStudent.add(new StudentObjects(972, "Sirius Black", "12 Grimmauld Place"));
newStudent.add(new StudentObjects(125, "Remus Lupin", "12 Grimmauld Place"));
newStudent.add(new StudentObjects(783, "Neville Longbottom", "Hogwarts Castle"));
newStudent.add(new StudentObjects(168, "Luna Lovegood", "24 Ottery St Catchpole"));
newStudent.add(new StudentObjects(224, "Severus Snape", "12 Spinner's End"));
newStudent.add(new StudentObjects(991, "Minerva McGonagall", "Hogwarts Castle"));
Collections.sort(newStudent, new sortByName());
System.out.println("Students sorted by name: ");
for (i=0; i<newStudent.size(); i++) {
System.out.println(newStudent.get(i));
}
System.out.println("");
Collections.sort(newStudent, new sortByRollNo());
System.out.println("Students sorted by roll number: ");
for (i=0; i<newStudent.size(); i++) {
System.out.println(newStudent.get(i));
}
}
}
【问题讨论】:
-
错误是什么?可以发一下吗?
-
我没有收到错误/异常。
-
始终在问题中包含错误。我们不喜欢猜测。
标签: java sorting arraylist comparator