shakeshuck
shakeshuck

Reputation: 125

Initializing a three dimensional array of arraylist in Java

I have a multidimentional array, as:

private static ArrayList [] [] pVTable = new ArrayList [35] [12];

My first try to initialize it was:

for (ArrayList[] x : pVTable) {
    for (ArrayList y : x) {
        y = new ArrayList<TableValue>();
    }
}

which didn't work.

I ended up doing it more manually, as in:

for ( int i = 0; i < pVTable.length; i++) {
    for ( int j = 0; j < pVTable[0].length; j++) {
        pVTable [i] [j] =  new ArrayList<TableValue>();
    }
}

which works fine.

Although I have a solution, I was wondering why the first (more elegant) piece of code doesn't do the same job?

Upvotes: 0

Views: 3154

Answers (4)

Eli Acherkan
Eli Acherkan

Reputation: 6411

In the first snippet, if we strip away the syntactic sugar of the foreach operator (:), the code translates to:

for (int xIndex = 0; xIndex < pVTable.length; xIndex++) {
    ArrayList[] x = pVTable[xIndex];
    for (int yIndex = 0; yIndex < x.length; yIndex++) {
        ArrayList y = x[yIndex];
        y = new ArrayList<TableValue>();
    }
}

As you can see, nothing is ever assigned to the actual array – only to the temporary y variable.

Upvotes: 1

NimChimpsky
NimChimpsky

Reputation: 47290

You are mixing ArrayList (part of collections api) with Arrays, which is rather confusing (for me anyway)

I would suggest something like this instead :

List<Point> myShape =  new ArrayList<Point>;

Where point contains two ints representing X and Y.

Upvotes: 1

Kane
Kane

Reputation: 4157

The scope of the first is incorrect. y is just a placeholder variable. Changing that doesn't change the underlying object, just the object that y refers to. You can see the same problem in the following code snippet:

public static  int x = 2;

public static void foo(int y) {
    y = 3;//does nothing outside of foo
}

public static void main(String[] args) {
    System.out.println(x);//prints 2
    foo(x);
    System.out.println(x);//prints 2, x hasn't changed.
}

Upvotes: 0

Roman Byshko
Roman Byshko

Reputation: 9002

In the first example your code although modifies y does not change x.

Upvotes: 1

Related Questions