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.

1
  • 1
    Your class is named gridCell not grid right? Commented May 12, 2016 at 22:59

1 Answer 1

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[][]

Sign up to request clarification or add additional context in comments.

5 Comments

Yes, that is correct. I did intend grid to be a variable (array) containing gridcell items within it.
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.
That's because arrays are 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.
Thinking a bit more, you're using a 2 dimensional array, so this question might be better for you. System.arraycopy() is really designed for single-dimension arrays.
OK, arraycopy got it working. Thanks for the pointers in the right direction.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.