0

I have a 2D array containing a class for each cell to contain info; ie

class gridCell {
    int value;
    Boolean valid;
    int anotherValue;
}

gridCell[][] grid=new gridCell[50][50];

This works well and once initialized I can access the array by using

grid[10][10].value=42;

My problem is I want to create a stack or arraylist to store the grid array state at various times. When I try and create an arraylist by

ArrayList<grid> gridList=new ArrayList<grid>();

I get the error that grid is not a class. Same deal if I try and use it in a stack

Stack<grid> gridStack = new Stack<grid>();

So how can I declare the grid so it can be added to a stack or arraylist?

Any help appreciated.

Some1Else
  • 715
  • 11
  • 26

1 Answers1

1

You need to declare the ArrayList type as the exact type you want to save. Since you want to save the grid array, you just need to pass the array type:

ArrayList<gridCell[][]> gridList = new ArrayList<gridCell[][]>();

You appear to be a little confused between types and variables. In your declaration

gridCell[][] grid = new gridCell[50][50];,

you are are declaring a variable grid of type gridCell[][]

adelphus
  • 10,116
  • 5
  • 36
  • 46
  • Yes, that is correct. I did intend grid to be a variable (array) containing gridcell items within it. – Some1Else May 12 '16 at 23:03
  • That declaration worked fine. How do I add the current grid array to the list? Using gridList.add(grid) doesn't seem to make a proper copy of the current grid array. – Some1Else May 12 '16 at 23:58
  • That's because arrays are [reference types](http://stackoverflow.com/questions/8790809/whats-the-difference-between-primitive-and-reference-types). If you want to store successive increments of the grid array, you need to create a copy yourself before adding it. `System.arraycopy()` should help you out. – adelphus May 13 '16 at 00:03
  • 1
    Thinking a bit more, you're using a 2 dimensional array, so [this question](http://stackoverflow.com/questions/5617016/how-do-i-copy-a-2-dimensional-array-in-java) might be better for you. `System.arraycopy()` is really designed for single-dimension arrays. – adelphus May 13 '16 at 00:09
  • OK, arraycopy got it working. Thanks for the pointers in the right direction. – Some1Else May 13 '16 at 00:20