【问题标题】:Getting ClassCastException while trying to do Ordered Insertion in ArrayList尝试在 ArrayList 中进行有序插入时获取 ClassCastException
【发布时间】:2018-04-02 02:45:15
【问题描述】:

公开课学生 { 私人 int 学生 ID; //学生的身份证号 私有字符串名称; // 学生姓名 私人双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

【问题讨论】:

    标签: arraylist casting insertion-sort


    【解决方案1】:

    您应该将 Collections.sort() 与比较器一起使用,而不是按照您的方式对列表进行排序

    Sorting Java objects using multiple keys

    【讨论】:

    • 很遗憾我不能使用收藏品,因为我们不允许这样做,这是学校作业!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-04
    • 2017-12-24
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 2017-04-20
    相关资源
    最近更新 更多