Forbidden to create shared array in Java

I thought I figured out that you can't create arrays of generic classes in Java, but a few examples I've seen lately really confused me. Can someone please explain? Thank!

I have a generic class defined as: public class Bag<Item> implements Iterable<Item>

Now in the EdgeWeightedGraph class (below) I create a Bag array and it compiles just fine. If Bag weren't a generic class, I know it should have been fine, but here it is. Then why isn't the compiler throwing an error?

public class EdgeWeightedGraph {

private final int V;
private final Bag[] adj;

    public EdgeWeightedGraph(int V) {
        this.V = V;
        adj = new Bag[V];
    }
}

      

While it raises an error in another generic class defined as:

public class MinPQ<Key extends Comparable<Key>> {

private Key[] pq;

    public MinPQ() {
        pq = new Key[2];
    }
}

      

+3


source to share


2 answers


In EdgeWeightedGraph

this line does not create a general array.

adj = new Bag[V];

      

It creates an array of raw type that is allowed. Bag

is a class, not a type parameter.



However, in MinPQ

, Key

is a type parameter, not a class, so this line tries to create a generic array and is a compiler error.

pq = new Key[2];

      

+3


source


Bag

is the raw type. It's not common. A typical type is, for example Bag<Integer>

.

So the following compilations:

adj = new Bag[V];  // compiles

      



but the following:

adj = new Bag<Integer>[V]; // error

      

As for Key

, it is a type parameter, not a raw type, for example Bag

.

+2


source







All Articles