You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 12:05:17