java.util.PriorityQueue.toArray() 方法
描述
toArray(T[] a) 方法用于返回一个包含此队列中所有元素的数组。
声明
以下是 java.util.PriorityQueue.toArray() 方法的声明。
public <T> T[] toArray(T[] a)
参数
a − 要存储队列元素的数组。
返回值
该方法调用返回一个包含此队列中所有元素的数组。
异常
ArrayStoreException − 如果指定数组的运行时类型不是此队列中每个元素的运行时类型的超类型,则引发。
NullPointerException − 如果指定的数组为空,则抛出。
示例
下面的例子展示了 java.util.PriorityQueue.toArray() 的用法。
package com.tutorialspoint;
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