Rohit Agarwal
Rohit Agarwal

Reputation: 420

generic array creation error

I am trying to make a Graph class with generic vertices and adjacency lists and I am getting a generic array creation error at line 10 of the following code. Earlier I was getting the same error at line 11 but it was solved by casting. But this error remains. What is wrong in the code?

import java.util.HashSet;

public class Graph<T> {
    private int numVertices;
    private T[] vertex;
    private HashSet<T>[] adjacent;

    public Graph(int numVertices) {
            this.numVertices = numVertices;
            vertex = (T[]) new T[numVertices];
            adjacent = (HashSet<T>[]) new HashSet[numVertices];
    }
}

Upvotes: 4

Views: 1414

Answers (3)

newacct
newacct

Reputation: 122429

You can't create an array of an unknown type (because an array contains its component type at runtime). But for your purpose you just need to create an Object[], which can contain any object.

You have two options:

  1. Use a variable of type Object[]. You may have to cast to T when you get elements out and want to use it as a T.
  2. Use a variable of type T[] (vertex = (T[]) new Object[numVertices];). This has the convenience of not having to cast to T when you get things out. However, you have to make sure not to pass or return this reference to code outside of the class that expects a T[], which will cause a class cast exception.

Upvotes: 1

Jeffrey
Jeffrey

Reputation: 44808

You can't create generic arrays in java because of type erasure.

However, you can use Array.newInstance(Class<T>, int) to create one for you. You will have to cast the returned Object to T[].

/e1
This still leaves the the problem of getting a Class<T> object. The best (only way I can think of) to do this is to have another parameter in your constructor which takes the class object.

Upvotes: 2

Michał Šrajer
Michał Šrajer

Reputation: 31182

Don't mix arrays with collections. Use just collections:

private List<HashSet<T>> adjacent;

You can then choose to use ArrayList as a List implementation. It's same efficient and more flexible.

Upvotes: 1

Related Questions