Consider a case where we can define a graph with the help of a List<List<Integer>> where list at index 0 will be the adjacency list of vertex 0 and so on for 1,2,3 and further.
Now if I declare such adjacency list as follows,
// initialize adjacency list
List<List<Integer>> adjList = new ArrayList<List<Integer>>(n);
In this case, why do I need to initialize each list as follows,
// initialize vertices
for (int i = 0; i < n; i++)
adjList.add(i, new ArrayList<Integer>());
This loop is only adding a new list at each index i, where n = number of vertices in a graph.
Doesn't the initial declaration mean that the main list will have a list at index 0 and then again another list at index 1 and so on?
I mean, I can understand the use of this loop, if I am declaring a graph with the help of an array of lists as follows,
ArrayList[] graph = new ArrayList[n];
then in this case, yes, I will definitely need a loop to initialize each vertex's adjacency list but why do we need to initialize in this initial case as well?
What if I declare the array as follows? Would that make any difference with the loop?
1. List<List<Integer>> adjList = new ArrayList<>(n);
2. List<List<Integer>> adjList = new ArrayList<List<List<Integer>>(n);
Please help me, what is the conceptual error that I am making to understand this?