打印优先队列的内容 [英] Print content of priority queue

查看:47
本文介绍了打印优先队列的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使print_queue在Java中正常工作?这是我自己的队列实现.

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

使用 Iterator()可以正常工作,只是它会以随机顺序打印数字.

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

}

我尝试使用 toArray(),但是它返回了 Object [] ,我不知道该如何遍历:

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

推荐答案

使用Iterator()可以正常工作,只是它以随机顺序打印数字.

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

这就是它说的将在Javadoc中执行的操作.在 PriorityQueue 中获得排序的唯一方法是使用 poll() remove()方法.

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.

这篇关于打印优先队列的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆