Gus*_*Gus 1 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
}
}
Run Code Online (Sandbox Code Playgroud)
当我只添加一个"学生"时没有问题,但是当我尝试捕获第二个时,应用程序会抛出此异常
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)
Run Code Online (Sandbox Code Playgroud)
有人可以解释我在哪里/为什么是问题?我花了很多时间在网上寻找解决方案,我找不到它,我需要一些帮助......坦克帮助我
如果您不提供自定义Comparator,PriorityQueue则对其保留的对象使用自然顺序.也就是说,它希望你的对象是Comparable彼此.你的Student班级似乎没有实施Comparable.
所以有两个选择:
Comparator用于比较Student对象的自定义Student类Comparable<Student>使用适当的逻辑实现