创建优先队列对象: 使用 PriorityQueue 类来创建一个优先队列的实例。你可以指定元素的比较器(Comparator),也可以使用元素的自然顺序(实现 Comparable 接口)。
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
或者,如果你需要自定义比较器:
PriorityQueue<Integer> customPriorityQueue = new PriorityQueue<>(Comparator.reverseOrder());
添加元素: 使用 add() 或 offer() 方法将元素添加到优先队列中。元素将根据其优先级进行排序。
priorityQueue.add(5);
priorityQueue.add(2);
priorityQueue.add(8);
访问和移除元素: 使用 poll() 方法来访问并移除具有最高优先级的元素。你也可以使用 peek() 方法来查看但不移除最高优先级的元素。
int highestPriorityElement = priorityQueue.poll();
或者只查看而不移除:
int highestPriorityElement = priorityQueue.peek();