gpt4 book ai didi

尽管实现了 Comparable 接口(interface),但 Java ClassCastException 错误

转载 作者:行者123 更新时间:2023-12-01 23:26:45 26 4
gpt4 key购买 nike

我正在做一个类(class)作业,它接受一个或多个学生的姓氏、名字和分数,将它们存储在一个数组中,然后按姓氏(如果姓氏相同则按名字)的字母顺序排序。我们需要使用一个实现 Comparable 接口(interface)的 Student 类。当我到达代码的 Arrays.sort 部分时,我收到一个 ClassCastException,指出“Student 无法转换为 java.lang.Comparable”。我已经搜索和审查,尝试使用 implements Comparable<Student> ,清理并构建,但错误仍然存​​在。任何帮助或提示表示赞赏。

错误:

Exception in thread "main" java.lang.ClassCastException:
studentscoreapp.Student cannot be cast to java.lang.Comparable
at java.util.Arrays.mergeSort(Arrays.java:1144)
at java.util.Arrays.sort(Arrays.java:1079)
at studentscoreapp.StudentScoreApp.main(StudentScoreApp.java:35)
Java Result: 1 BUILD SUCCESSFUL (total time: 12 seconds)

这是我的学生类(class):

public class Student implements Comparable
{

private String lastName;
private String firstName;
private int score;

public Student(String fName, String lName, int s)
{
fName = firstName;
lName = lastName;
s = score;
}

public String getLastName()
{
return lastName;
}

public void setLastName(String lastName)
{
this.lastName = lastName;
}

public String getFirstName()
{
return firstName;
}

public void setFirstName(String firstName)
{
this.firstName = firstName;
}

public int getScore()
{
return score;
}

public void setScore(int score)
{
this.score = score;
}

@Override
public int compareTo(Object obj)
{
Student sent = (Student) obj;
if (sent.lastName.equals(this.lastName))
{
return this.firstName.compareToIgnoreCase(sent.firstName);
}
else return this.lastName.compareToIgnoreCase(sent.lastName);
}

@Override
public String toString()
{
return lastName + firstName + score;
}
}

可比较接口(interface):

public interface Comparable
{

int compareTo(Object obj);
}

和我的主要:

import java.util.Arrays;

公开课StudentScoreApp {

public static void main(String[] args)
{
String firstName;
String lastName;
int score;

System.out.println("Welcome to the Student Scores Application");
int numStudents = Validation.getInt("Enter # of Students: ");
Student[] studentArray = new Student[numStudents];

int i;
for (i = 0; i < numStudents; i++)
{
firstName = Validation.getString("Student [" + (i + 1) + "] first name: ");
lastName = Validation.getString("Student [" + (i + 1) + "] last name: ");
score = Validation.getInt("Student [" + (i + 1) + "] score: ", 0, 100);
studentArray[i] = new Student(firstName, lastName, score);
}


Arrays.sort(studentArray); //line 35

System.out.println();

//take each obj of the array and print the student info
for (Student obj : studentArray)
{
System.out.println(obj.toString());
}

}
}

最佳答案

Arrays.sort() 接受一个对象数组,这些对象是 java.lang.Comparable 的子类型。在您的代码中,您创建了自己的 Comparable 接口(interface),虽然它的行为方式与 java.lang.Comparable 相同,但并不是同一个接口(interface)。

关于尽管实现了 Comparable 接口(interface),但 Java ClassCastException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19872133/

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