【发布时间】:2021-08-01 04:58:45
【问题描述】:
我对 java 很陌生,这也是我在 StackOverflow 上的第一个问题。我正在尝试创建一个游戏,其中由5x5 2D 数组表示的棋盘可以在每个方格上最多堆叠 4 个筹码。
import java.util.Stack;
public class Trying {
public static void main(String[] args) {
// How would I get these stacks..
Stack<String> stackR1C1 = new Stack<>();
Stack<String> stackR1C2 = new Stack<>();
Stack<String> stackR1C3 = new Stack<>();
Stack<String> stackR1C4 = new Stack<>();
Stack<String> stackR2C1 = new Stack<>();
Stack<String> stackR2C2 = new Stack<>();
Stack<String> stackR2C3 = new Stack<>();
Stack<String> stackR2C4 = new Stack<>();
Stack<String> stackR3C1 = new Stack<>();
Stack<String> stackR3C2 = new Stack<>();
Stack<String> stackR3C3 = new Stack<>();
Stack<String> stackR3C4 = new Stack<>();
Stack<String> stackR4C1 = new Stack<>();
Stack<String> stackR4C2 = new Stack<>();
Stack<String> stackR4C3 = new Stack<>();
Stack<String> stackR4C4 = new Stack<>();
// Into this 2D array
String[][] boardArray = {
{" ", "c1 ", "c2 ", "c3 ", "c4 "},
{"r1 ", "__|", "__|", "__|", "__|"},
{"r2 ", "__|", "__|", "__|", "__|"},
{"r3 ", "__|", "__|", "__|", "__|"},
{"r4 ", "__|", "__|", "__|", "__|"}};
}
}
当我尝试简单地将堆栈添加到它们在数组中的位置时,我得到了这个错误:
error: incompatible types: Stack<String> cannot be converted to String
【问题讨论】:
-
是的,但您需要将它们存储在正确类型的数组中:
Stack<String>[][],而不是String[][]。话虽如此,数组和泛型不能很好地配合使用,因此您应该考虑改用List<List<Stack<String>>>。
标签: java arrays multidimensional-array stack