2014-04-08 2 views
3

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) ; 
+0

대기열이 대기열로되어 있습니까, 아니면 PriorityQueue가되어야합니까? 그들은 두 가지 다른 일을합니다. –

+0

@WillNewton, 실제로 대기열에 있지만 자바 API에서 std.priority 대기열을 사용합니다. – ERJAN

답변

7

숫자는 임의의 순서로 표시됩니다.

정확히 Javadoc에서 수행 할 것이라고합니다. PriorityQueue에서 주문을받는 유일한 방법은 poll() 또는 remove() 방법을 사용하는 것입니다.

+1

@downvoter이 답변은 Javadoc과 일치합니다. 네 입장? – EJP

+1

네, 그 이유를 보지 못했습니다 - 나, 주제 시동기 +1 – ERJAN

+0

ejp를 제공하지만, 내가 사용하면 제거() - 내가 큐 자체에서 요소를 삭제, 어떻게 든 그것을 저장하고 다시 복사해야합니까 remove() 후에? – ERJAN