Java优先队列元素添加异常:输出顺序与预期不符求助
排查Java优先队列排序异常问题
我正在解决Java优先队列相关题目,已实现包含id、Name、cgpa属性及Getter方法的Student类。
现有代码实现
Priorities类
class Priorities{ private List<Student> list_student = new ArrayList<>(); class CheckCondition implements Comparator<Student>{ @Override public int compare(Student o1, Student o2) { if(o1.getCGPA() < o2.getCGPA()){ return 1; }else if(o1.getCGPA() > o2.getCGPA()){ return -1; }else{ if(o1.getName().compareTo(o2.getName()) < 0) { return 1; }else if(o1.getName().compareTo(o2.getName()) > 0){ return -1; }else { if(o1.getID() < o2.getID()){ return -1; }else { return 1; } } } } } public List<Student> getStudents(List<String> events, int capacity){ Queue<Student> stringQueue = new PriorityQueue<>(capacity, new CheckCondition()); if(events.isEmpty()){ System.out.println("EMPTY"); } for(String element: events){ List<String> stringList = List.of(element.split(" ")); if(stringList.get(0).equalsIgnoreCase("ENTER")){ Student new_student = new Student(Integer.parseInt(stringList.get(3)), stringList.get(1), Double.parseDouble(stringList.get(2))); stringQueue.add(new_student); }if(stringList.get(0).equalsIgnoreCase("SERVED") ){ stringQueue.poll(); } } stringQueue.stream().forEach(element -> list_student.add(element)); return list_student; } }
Main类
public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); List<String> events = new ArrayList<>(); Integer capacity = sc.nextInt(); sc.nextLine(); for (int i = 0; i < capacity; i++) { events.add(sc.nextLine()); } Priorities priorities = new Priorities(); List<Student> students = priorities.getStudents(events, capacity); for(Student element: students){ System.out.println(element.getName()); } } }
问题现象
测试时输出顺序与预期不符:
预期输出:
Dan Ashley Shafaet Maria
实际输出:
Dan Ashley Maria Shafaet
添加学生Anik时,Shafaet和Maria的位置出现错误,请求排查原因。
内容的提问来源于stack exchange,提问作者Hung Nguyen
相关产品推荐
相关产品推荐

