4

I thought I understood that you could not create arrays of generic classes in Java but a few examples I have seen lately have really confused me. Can someone explain? Thanks!

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

Now in a class called EdgeWeightedGraph (below), I am making an array of Bag and that's compiling just fine. If Bag wasn't a generic class, I know that this should have been fine but here, it is. Then why is the compiler not 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 is throwing an error in another generic class defined as:

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

private Key[] pq;

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

2 Answers 2

3

In EdgeWeightedGraph, this line does not create a generic array.

adj = new Bag[V];

It is creating an array of a raw type, which is allowed. Bag is a class, not a type parameter.

However, in MinPQ, Key is a type parameter, not a class, so this line attempts to create a generic array and is a compiler error.

pq = new Key[2];
Sign up to request clarification or add additional context in comments.

Comments

2

Bag is a raw type. It is not generic. A generic type is for instance Bag<Integer>.

So the following compiles:

adj = new Bag[V];  // compiles

but the following doesn't

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

As for Key, it is a type parameter, not a raw type like Bag.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.