0

I am trying to create adjacency list for graph by creating array of arraylist of type edge(include source,dest,weight) as in code below :

public class Main {
    
static class Edge{
    
    int s;
    int d;
    int wt;
    
    Edge(int src,int des,int weight)
    {
        this.s = src;
        this.d = des;
        this.wt = weight;
        
    }
}
    
    public static void main(String[] args) throws Exception
    {
        //creating array of arraylist of type edge

        ArrayList<Edge>[] graph = new ArrayList[7];
        
        //Doubt regarding this line ,as why is it essential?
        graph[0] = new ArrayList<Edge>();
        
        //creating edge object 
        Edge e = new Edge(0,1,10);

      //adding it into arraylist
        graph[0].add(e);
        
        
        
    }

Since I have created array of arraylist of type edge , I think I can directly add into arraylist like graph[0].add(e) without writing graph[0] = new ArrayList();

but it isn't working without it. Why I need to give above statement when my array is of arraylist so can't I add the elements directly?

1 Answers1

0

This code declares graph to be an array of 7 ArrayList, with its elements initially (as in all arrays) set to their default values - null for objects, 0 for integers, false for booleans:

    ArrayList<Edge>[] graph = new ArrayList[7];

You can test it by adding this line below, or by stepping through with a debugger:

    System.err.println(graph[0]); // prints "null"

Your new ArrayList[7] only reserved space for an array of (ArrayList) objects, but did not reserve space for the 7 new ArrayLists you want to add. This allows you, for instance, to add subclasses of ArrayList to your array, or leave some slots with a null value, or add the same ArrayList to several slots. All of these options can be useful in some cases, so the compiler and language do not create empty new elements unless you explicitly them to do so. I would recommend using a loop:

    ArrayList<Edge>[] graph = new ArrayList<>[7];
    for (int i=0; i<graph.length; i++) {
        graph[i] = new ArrayList<Edge>();
    }
tucuxi
  • 17,561
  • 2
  • 43
  • 74