JamesA JamesA - 5 months ago 10
Java Question

How do you assign values to an ArrayList member variable of a Java Class during build method?

I have a class with an ArrayList as a member variable

public class Tile {
private final String Name;
private final ArrayList<Integer> sides;

public Tile (String name, int up, int right,int down, int left){

this.Name = name;
this.sides.add(up);

}
}


So when I create a Tile object I want to set the up, right, down, left values into a 4 object array for the Tile Class. With the above code I'm getting an error from NetBean "variable sides might not have been initialized". I'm not sure what that means, because I'm attempting to initialize it with the build method.

Looking for help from NetBean ended up with the following, which gets the same error.

this.sides.set(0, up);


I'm new to Java so if someone could provide some I'm looking for some instruction on the concepts I'm failing to understand.

Thank you

Answer

You got the message variable sides might not have been initialized which explained your problem already. You have to initialize the sides array list first.

Like this:

private final ArrayList<Integer> sides = new ArrayList<>();

Or within the constructor before you add objects to your sides list, like this:

public Tile (String name, int up, int right,int down, int left){
    sides = new ArrayList<Integer>();
    this.Name = name;
    this.sides.add(up);
}