尽管实现了Comparable接口的Java ClassCastException错误

时间:2013-11-09 03:47:08

标签: java arrays classcastexception comparable

我正在进行一项课程作业,该课程作业接受一个或多个学生的姓氏,名字和分数,将它们存储在一个数组中,然后按姓氏的字母顺序排序(如果姓氏相同,则按字母顺序排序)。 我们需要使用实现Comparable接口的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)

这是我的学生班:

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

Comparable接口:

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

    }
}

1 个答案:

答案 0 :(得分:3)

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