Home > Software design >  Java instance variable array size based on another instance variable
Java instance variable array size based on another instance variable

Time:09-17

I am trying to make a graph class that has an array as an instance variable, but the size of this array is dependent on another instance variable which will be intialized in the constructor. Here's a Simple example:

public class Graph {
//Number of Vertices and Edges:
private int V;
private int E;
//Visited/Unvisited list:
private int[] visitedList = new int[V];

//Constructor:
public Graph(int V){
        this.V = V;
        this.E = 0;
        for (int i = 0; i < V; i  ) { //Initialize all vertices as 0
            visitedList[i] = 0;
        }
}

As you can see, the size of the visitedList will be dependent on the variable V which we initialize via the constructor. However, I get an error inside the constructor when I try to initialize the visitedList after getting the value of V. Is there a proper way to intialize the array visitedList such that the size follows V and I can intiailize all the elements to 0? Or do I need to do it some other way outside the constructor with another method that perhaps intializes the visitedList? Any help is welcome, thank you!

CodePudding user response:

You currently construct the array before the other statements in your constructor run. You need to change that

private int[] visitedList; // V is 0 at this point.

//Constructor:
public Graph(int V){
        this.V = V;
        this.E = 0;
        this.visitedList = new int[V];
        // default initial value in an int[] **is** zero.
}
  • Related