Jonzi Jonzi - 1 year ago 102
Java Question

Creating array of PriorityQueues

Hello guys I am stuck on this silly problem.

I need PriorityQueue[]

I have tried:

smth = new PriorityQueue<Integer>[n];

Err: Generic array creation

smth = (PriorityQueue<Integer>[])new Object[n];

Err: [unchecked]unchecked cast

Uhh am I missing something??

Answer Source

You cannot create an array of generics, and cannot cast Object[] into what you want either, you have to cast a PriorityQueue[] into PriorityQueue<Integer>[]:

PriorityQueue<Integer>[] smth = (PriorityQueue<Integer>[])new PriorityQueue[n];

If you want to remove the warning, just add @SuppressWarnings("unchecked") before the function.

A more complete example:

public class Main<T> {

    public static <T> void main(String[] args) {
        // Impossible
        T[] a1 = new T[42];

        // Ok, with unsafe cast warning
        T[] a2 = (T[]) new Object[42];

        // Impossible
        List<T>[] l1 = new List<T>[42];

        // Ok, with unsafe cast warning
        List<T>[] l2 = (List<T>[]) new List[42];

Casting works in only one way: you can cast a subclass into its parent class but you cannot cast a parent class into its subclass:

public static <T> void main(String[] args) {
    // Works fine
    Object o = (Object) new Integer(0);

    // Compiles but throws an exception
    Integer i = (Integer) new Object();

    // Same goes for arrays, you can cast Integer[] into Object[]
    // but not do the opposite
    Object[] a1 = (Object[]) new Integer[1]; // OK
    Integer[] a2 = (Integer[]) new Object[1]; // Not OK
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download