我参加了第二次计算机编程课程,并被要求编写一个实现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));
            }
}
}

最佳答案

将这两个类放在同一文件或不同文件中的主类“学生对象”之外,或将它们作为内部类。

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;
    }
}

关于java - Java中的2个比较器类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60872493/

10-11 05:20