英文:
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<Char>[][] objectGrid = (Stack<Char>[][]) 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 < width; i++) {
for (int j = 0; j < height; j++) {
objectGrid[i][j] = new Stack<Char>();
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论