PriorityQueue:无法将学生强制转换为java.lang.com
我使用PriorityQueue结构获取用户设置的一些字段,下面是部分代码:PriorityQueue:无法将学生强制转换为java.lang.com,java,priority-queue,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>(); publ
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
}
}
谁能解释一下问题出在哪里/为什么?我花了很多时间在网上寻找解决方案,但我找不到,我需要一些帮助。。。
感谢您对我的帮助如果您不提供自定义的
比较器
,优先级队列
会对它所持有的对象使用自然排序。也就是说,它希望您的对象彼此具有可比性。您的学生
类似乎没有实现可比
因此,有两种选择:
- 实现并提供一个自定义的
,用于比较比较器
对象学生
- 让你的
班级用适当的逻辑实现学生
可比性
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;
}
}
公共班级学生实施可比{
私人长id;
私有字符串名;
私有字符串lastName;
//getter、setter和构造函数
@凌驾
公共国际比较(学生){
if(this.id==student.getId()){
返回0;
}else if(this.id
如何实现可比较的方法?对不起,这是我第一次使用它structure@Gus是类javadoc。是一个示例。
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;
}
}