gpt4 book ai didi

java - Java中的2个比较器类

转载 作者:行者123 更新时间:2023-12-02 08:49:36 24 4
gpt4 key购买 nike

我正在上第二门计算机编程课,并被要求编写一个实现 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));
}
}
}

最佳答案

将这两个类放在主类“Student Objects”之外的同一文件或不同文件中,或者将它们设为内部类。

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com