2D堆栈实现,出现空指针异常。

huangapple go评论94阅读模式
英文:

2D Stack implementation, getting NullPointerException

问题

我尝试实现一个类似这样的二维堆栈
private Stack<Char>[][] objectGrid = (Stack<Char>[][]) new Stack[width][height]
然而,当我尝试将一个元素推入堆栈时,我一直收到空指针异常
(objectGrid[x][y]).push(ch)
我检查了调试器,发现 objectGrid[x][y] 为 null,所以我无法对其执行推入操作。上述的初始化是否有误,我应该使用循环来初始化堆栈数组的第二维度吗?

英文:

I try to implement a 2D Stack like this
private Stack&lt;Char&gt;[][] objectGrid = (Stack&lt;Char&gt;[][]) new Stack[width][height]

However, when I try to push an element to my stack, I keep getting NullPointerException
(objectGrid[x][y]).push(ch)
I checked the debugger, and figured that objectGrid[x][y] appears as null, so I can't do push on it. Is the above initialization wrong, should I do a for loop to initialize the second dimension of my stack array?

答案1

得分: 0

Add initialize loop to your code, like this:

for (int i = 0; i < width; i++) {
    for (int j = 0; j < height; j++) {
        objectGrid[i][j] = new Stack<Char>();
    }
}
英文:

Add initialize loop to your code, like this:

for (int i = 0; i &lt; width; i++) {
	for (int j = 0; j &lt; height; j++) {
		objectGrid[i][j] = new Stack&lt;Char&gt;();
	}
}

huangapple
  • 本文由 发表于 2020年10月27日 22:34:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/64556694.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定