gpt4 book ai didi

Java CompareTO 方法问题

转载 作者:行者123 更新时间:2023-12-01 06:52:24 24 4
gpt4 key购买 nike

我正在尝试用一个简单的java程序整理一个简单的学生标记列表,但是我得到了

Exception in thread "main" java.lang.ClassCastException: Student cannot be cast to java.lang.Comparable

public class Student {
public String name;
public int mark;


public Student(String name, int mark){
this.name=name;
this.mark=mark;
}


public int compareTo(Student o){
return this.mark-o.mark;


}
public String toString(){
String s = "Name: "+name+"\nMark: "+mark+"\n";
return s;
}

public static void main(String[] args) {
Student Class[] = new Student[9];
Class[0] = new Student("Henry",100);
Class[1] = new Student("Alex", 10);
Class[2] = new Student("Danielle",100);
Class[3] = new Student("Luke",10);
Class[4] = new Student("Bob",59);
Class[5] = new Student("Greg",76);
Class[6] = new Student("Cass",43);
Class[7] = new Student("Leg",12);
Class[8] = new Student("Bobe",13);



Arrays.sort(Class);
for(int i = 0;i<Class.length;i++){
System.out.println(Class[i]);

最佳答案

您的 Student必须实现 Comparable 接口(interface)才能使用 Arrays#sort 传递 Student[] 数组。您的类当前具有 compareTo 方法这一事实并不意味着它实现了此接口(interface),您必须声明:

public class Student implements Comparable<Student> {
//class definition...
}

关于Java CompareTO 方法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21834212/

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