gpt4 book ai didi

java - PriorityQueue : Student cannot be cast to java. lang.Comparable

转载 作者:行者123 更新时间:2023-11-29 10:01:22 25 4
gpt4 key购买 nike

我正在使用 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
}
}

当我只添加一个“学生”时没有问题,但是当我 try catch 第二个“学生”时应用程序抛出此异常

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)

有人可以向我解释问题出在哪里/为什么吗?我花了很多时间在网上寻找解决方案,但找不到,我在这里需要一些帮助...谢谢你帮助我

最佳答案

如果您不提供自定义 Comparator , PriorityQueue对其持有的对象使用自然排序。也就是说,它期望您的对象是 Comparable对彼此。你的Student类似乎没有实现 Comparable .

所以有两个选择:

  • 实现并提供自定义 Comparator用于比较 Student对象
  • 有你的Student类(class)工具Comparable<Student>具有适当的逻辑

关于java - PriorityQueue : Student cannot be cast to java. lang.Comparable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26416258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com