简体   繁体   中英

How do I make a Rows x Cols grid of individual instances

I have a class Box that represents one single box of a grid. Now, I'm trying to create a Rows x Cols grid of instances of the boxes.

I would like to have a 2d ArrayList of boxes. Something analogous to the array: coord[rows][cols] . So that when I write coord.get(5)(6) , I'm getting the box that is at row 5 and column 6 .

You could use an ArrayList of ArrayLists. Something like this:

ArrayList<ArrayList<Box>> grid = new ArrayList<ArrayList<Box>>();
grid.add(new ArrayList<Box>());
grid.get(0).add(new Box());
Box myBox = grid.get(0).get(0);

But note that this is pretty gross. Just use a 2D array.

You can create an array of Box, even a 2D (or 3D, 4D, ...) of Box:

Box[][] boxes = new Box[ROWS][COLS]; 

instead of

coord.get(5)(6);

you simply write

Box b = boxes[5][6]; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM