PriorityBlockingQueue toArray() method in Java
The toArray()
method in PriorityBlockingQueue
class is used to return an array containing all of the elements in this queue. The returned array elements are in no particular order.
Syntax:
public Object[] toArray()
Example:
PriorityBlockingQueue<Integer> pbq = new PriorityBlockingQueue<>();
pbq.add(10);
pbq.add(20);
pbq.add(30);
Object[] arr = pbq.toArray();
System.out.println(Arrays.toString(arr));
Output:
[10, 20, 30]
Another example with a custom object:
class Person implements Comparable<Person> {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public int compareTo(Person o) {
return Integer.compare(age, o.age);
}
}
PriorityBlockingQueue<Person> pbq = new PriorityBlockingQueue<>();
pbq.add(new Person("Alice", 25));
pbq.add(new Person("Bob", 30));
pbq.add(new Person("Charlie", 20));
Object[] arr = pbq.toArray();
System.out.println(Arrays.toString(arr));
Output:
[Person [name=Charlie, age=20], Person [name=Alice, age=25], Person [name=Bob, age=30]]
Note that the returned array is of type Object[]
. If you want an array of a specific type, you can pass an array of that type as an argument to the toArray()
method. For example:
Person[] arr = pbq.toArray(new Person[0]);
System.out.println(Arrays.toString(arr));
Output:
[Person [name=Charlie, age=20], Person [name=Alice, age=25], Person [name=Bob, age=30]]