简体   繁体   中英

Initialize a 2D array with stack - Java

I would like to declare a 2D array and each coordinate [x][y] will return a Stack. So, I started with this

    private Stack<Balloon>[][] location;

and I try to create memory space for it. I tried this, but I failed

    location = new Stack<Balloon>()[width][height];

should I do something like

for(int i=0; i < width; i++){
    for(int j=0; j < height; j++){
        location[i][j] = new Stack<Balloon>();
    }
}

or there is a special way to do it?

Hmm, based on your description, maybe this might work out better?

Map<Point, Stack<Balloon>> map = new HashMap<Point, Stack<Balloon>>();

A Point has an x and ay coordinate already, and is part of the standard library.

that way, you can query a specific stack by using:

int x = 1;
int y = 1;
Point point = new Point(x, y);
Stack<Balloon> balloons = map.get(point);
location = new Stack[width][height]; // remove generic
location = new Stack<Balloon>()[width][height]; // Invalid
location = new Stack<Balloon>[width][height]; // Valid!

You should then loop through if you don't want the values to be null.

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