3

This seems like basic question, but it has really confused me. I ma trying to represent the adjacency list of a graph. I have two questions :

public class Graph
{
    private final int V;
    private List<Integer>[] adj;

    public Graph(int V)
    {
        this.V = V;
        this.adj = (List<Integer>[]) new LinkedList[V];  // this works
    }
}

Question 1: when I do the below, it gives an error saying

Array type expected; found: 'java.util.LinkedList<java.lang.Integer>'
this.adj = (List<Integer>[]) new LinkedList<Integer>()[V];

I am creating a List of Integer arrays, right ?

Question 2: when I do this, it again gives an error saying generic array creation:

this.adj = (List<Integer>[]) new LinkedList<Integer>[V]; 

What is the problem with the last two approaches ? i think the first one is more correct.

jww
  • 83,594
  • 69
  • 338
  • 732
OneMoreError
  • 6,592
  • 17
  • 61
  • 102

2 Answers2

5

In (1), your expression is being parsed as

(new LinkedList<Integer>())[V]

which is attempting to index a freshly-created LinkedList, hence the error.

In (2), you are trying to make an array of generics. You can't do this. Instead, consider using some container type (like an ArrayList<List<Integer>>).

Community
  • 1
  • 1
nneonneo
  • 154,210
  • 32
  • 267
  • 343
0

You are trying to create an array of list of integer. That means each index can have multiple count. So, you need to initialize each index.

public Graph(int v)
    {
        V = v;
        adj = new List<int>[v];
        for (int i = 0; i < v; ++i)
            adj[i] = new List<int>();
    }