Array view of lists

This looks like the main question, but it really confused me. I am trying to present a graph adjacency list. 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 below it gives an error

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 that says creating a shared array:

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

      

What's the problem with the last two approaches? I think the first one is more correct.

+3


source to share


1 answer


In (1) your expression is parsed as

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

      



which is trying to index the newly created LinkedList

, hence the error.

In (2), you are trying to create an array of generics. You cannot do this . Consider using some type of container (for example ArrayList<List<Integer>>

) instead .

+4


source







All Articles