Java에서 print_queue가 올바르게 작동하도록하려면 어떻게해야합니까? 이것은 내 자신의 큐 구현입니다.우선 순위 큐의 내용을 인쇄하십시오. [java]
Iterator()를 사용하면 숫자가 임의의 순서로 인쇄된다는 점을 제외하고는 잘 동작합니다.
package data_structures_java ;
import java.util.Iterator;
import java.util.PriorityQueue ;
import java.util.* ;
public class Queue_implementation {
PriorityQueue<Integer> actual_queue ;
public Queue_implementation(){
actual_queue = new PriorityQueue<Integer>() ;
}
public void add(int num){
actual_queue.add(num) ;
}
public int remove(){
return actual_queue.remove() ;
}
public int peek(){
if(actual_queue.isEmpty()) return -1 ;
else return actual_queue.peek() ;
}
public int element(){
return actual_queue.element() ;
}
public void print_queue(){
PriorityQueue<Integer>copy = new PriorityQueue<Integer>();
copy.addAll(actual_queue) ;
Iterator<Integer> through = actual_queue.iterator() ;
while(through.hasNext()) {
System.out.print(through.next() + " ") ;
}
System.out.println() ;
actual_queue.addAll(copy) ;
}
public static void main(String[] args) {
Queue_implementation x = new Queue_implementation() ;
x.add(10) ;
x.add(9) ;
x.add(8) ;
x.add(7) ;
x.add(6) ;
x.print_queue() ;
}
}
나는 toArray()를 사용하려고하지만, 객체 [], 나는 통과하는 방법을 알고 '해달라고하는 반환은 인쇄를 제외하고 반복자는(), 잘 작동 사용
Object[] queue_object_array = x.toArray() ;
Arrays.sort(queue_object_array) ;
대기열이 대기열로되어 있습니까, 아니면 PriorityQueue가되어야합니까? 그들은 두 가지 다른 일을합니다. –
@WillNewton, 실제로 대기열에 있지만 자바 API에서 std.priority 대기열을 사용합니다. – ERJAN