Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

java - Print content of priority queue

How do I make the print_queue work properly in Java? This is my own implementation of a queue.

Using Iterator() works fine, except it prints numbers in random order.

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() ;
    }

}

I tried to use toArray() but it returns Object[], which I don't know how to traverse:

Object[] queue_object_array = x.toArray() ;
Arrays.sort(queue_object_array) ;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using Iterator() works fine, except it prints numbers in random order.

That's exactly what it says it will do in the Javadoc. The only way to get the ordering in the PriorityQueue is to use the poll() or remove() methods.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...