4

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];
    }
}
1
  • 3
    @downvoter: why is it downvoted? I can't see a problem with this question! Commented Sep 11, 2011 at 15:09

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Thanks.. Now I am not getting any errors just unchecked/unsafe operations warning.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.