尝试在ArrayList中执行有序插入时获取ClassCastException

时间:2018-04-02 02:45:15

标签: arraylist casting insertion-sort

公共班学生 {     private int studentId; //学生的身份证号码     私有字符串名称; //学生的名字     私人双gpa; //学生的平均成绩

/***************************************************************************
 * Student
 *   The constructor for the student class
 ***************************************************************************/
public Student(int id, String theName, double theGPA)
{
    studentId = id;
    name = theName;
    gpa = theGPA;
}  // constructor

/***************************************************************************
 * toString
 *   Convert the data in a student object into a String.
 ***************************************************************************/
public String toString()
{
    return String.format("%7d %-20s %4.2f", studentId, name, gpa);
}

/***************************************************************************
 * compareTo
 *   Compare the student id of this object to that of the given object.
 * parameters:
 *   student - the given student object
 * returns:
 *   -1 if this student id is the smaller of the two id's
 *   0 if the student id's are equal
 *   1 if this student id is the larger of the two id's
 ***************************************************************************/
public int compareTo(Student student)
{
    if(student.studentId<studentId)
    {
        return -1;
    }
    else if(student.studentId>studentId)
    {
        return 1;
    }
    else
        {
            return 0;
        }
}  // compareTo

} //班级学生

在主类中这是我尝试使用的方法:

public static void orderedInsert(ArrayList<Student>students, Student student)
{
    int size = students.size();
    int current = size -1;

    for(int i=1; i<students.size(); i++) {
        while (current >= 0 && students.get(current).compareTo(students.get(i)) > 0) {
            current--;
            students.add(current + 1, student);

        }
    }
}  // orderedInsert

1 个答案:

答案 0 :(得分:0)

不应按照您的方式对列表进行排序,而应使用Collections.sort()和比较器

Sorting Java objects using multiple keys