PriorityQueue:学生不能转换为java.lang.Comparable

时间:2014-10-17 00:54:07

标签: java priority-queue

我使用PriorityQueue结构来获取用户设置的一些字段,这是代码的一部分:

package gqg;

import java.util.Queue;

public class Student {
     //variables (ID, Name, ...), constructors, getters and setters...

Queue<Student> StudentQueue = new PriorityQueue<Student>();

public void Add() { //method to add the student at Queue
    for(int x=0; x<1; x++) {
        Student st = new Student();
        System.out.println("+---------------------------+\n"
                         + "|   Students Registration   |\n"
                         + "+---------------------------+");
        System.out.println("| Type the student's ID:");
        stu.setID(user.nextInt());
        System.out.println("| Type the student's name:");
        stu.setName(user.next());
        System.out.println("| Type the student's age:");
        stu.setAge(user.nextInt());
        //and other fields...

        StudentQueue.add(st);
    }
    System.out.println("Done. Student has been added successfuly\n");       
}

/* then I call Add(); in Menu();
 * this method also has Print(); Modify(); Eliminate(); those three works well
 * The only one problem is Add();
 */

public void Menu(){
    //... methods
}
}

当我只添加一个&#34; student&#34;时没有问题,但是当我尝试捕获第二个时,应用程序会抛出此异常

Exception in thread "main" java.lang.ClassCastException: gqg.Student cannot be cast to java.lang.Comparable     at
java.util.PriorityQueue.siftUpComparable(PriorityQueue.java:633)    at
java.util.PriorityQueue.siftUp(PriorityQueue.java:629)  at
java.util.PriorityQueue.offer(PriorityQueue.java:329)   at
java.util.PriorityQueue.add(PriorityQueue.java:306)     at
gqg.Student.AddQueue(Student.java:374)  at
gqg.Student.Menu(Student.java:592)  at
gqg.MainClass.main(MainClass.java:7)

有人可以解释我在哪里/为什么会出现这个问题?我花了很多时间在网上寻找解决方案而且我找不到它,我需要一些帮助...... 坦克你帮助我

2 个答案:

答案 0 :(得分:8)

如果您没有提供自定义ComparatorPriorityQueue会对其拥有的对象使用自然排序。也就是说,它希望您的对象彼此为Comparable。您的Student课程似乎没有实施Comparable

所以有两个选择:

  • 实施并提供自定义Comparator,用于比较Student个对象
  • 让您的Student类实现Comparable<Student>具有适当的逻辑

答案 1 :(得分:0)

例如:

public class Student implements Comparable<Student> {

private Long id;
private String firstName;
private String lastName;

//getter,setter and constructor

@Override
public int compareTo(Student student) {
    if (this.id == student.getId()) {
        return 0;
    } else if (this.id < student.getId()) {
        return 1;
    } else {
        return -1;
    }
}