目录

<T> T[] toArray(T[] a)

描述 (Description)

toArray(T[] a)方法用于返回包含此队列中所有元素的数组。

声明 (Declaration)

以下是java.util.PriorityQueue.toArray()方法的声明。

public <T> T[] toArray(T[] a)					 

参数 (Parameters)

a - 要存储队列元素的数组。

返回值 (Return Value)

  • 方法调用返回一个包含此队列中所有元素的数组。

异常 (Exception)

  • ArrayStoreException - 如果指定数组的运行时类型不是此队列中每个元素的运行时类型的超类型,则抛出此异常。

  • NullPointerException - 如果指定的数组为null,则抛出此异常。

例子 (Example)

以下示例显示了java.util.PriorityQueue.toArray()的用法

package com.iowiki;
import java.util.*;
public class PriorityQueueDemo {
   public static void main(String args[]) {
      // create priority queue
      PriorityQueue < Integer >  prq = new PriorityQueue < Integer > (); 
      // insert values in the queue
      prq.add(6);  
      prq.add(9);
      prq.add(5);
      prq.add(64);
      prq.add(6);
      System.out.println("Priority queue values are: "+ prq);
      // create arr1
      Integer[] arr1 = new Integer[5];
      // use toArrsy() method
      Integer[] arr2 = prq.toArray(arr1); 
      System.out.println("Value in arr1: ");
      for ( int i = 0; i<arr1.length; i++ ) {  
         System.out.println("Value: " + arr1[i]) ; 
      }
      System.out.println("Value in arr2: ");
      for ( int i = 0; i<arr2.length; i++ ) {  
         System.out.println("Value: " + arr2[i]) ; 
      }
   }
}

让我们编译并运行上面的程序,这将产生以下结果。

Priority queue values are: [5, 6, 6, 64, 9]
Value in arr1: 
Value: 5
Value: 6
Value: 6
Value: 64
Value: 9
Value in arr2: 
Value: 5
Value: 6
Value: 6
Value: 64
Value: 9
↑回到顶部↑
WIKI教程 @2018