[英]Initialize a 2D array with stack - Java
I would like to declare a 2D array and each coordinate [x][y] will return a Stack. 我想声明一个2D数组,每个坐标[x] [y]将返回一个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. 一个
Point
已经具有x和ay坐标,并且是标准库的一部分。
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. 如果您不希望这些值为null,则应该遍历。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.