【问题标题】:Is it possible to create a 2D array of stacks?是否可以创建二维堆栈数组?
【发布时间】: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&lt;String&gt;[][],而不是String[][]。话虽如此,数组和泛型不能很好地配合使用,因此您应该考虑改用List&lt;List&lt;Stack&lt;String&gt;&gt;&gt;

标签: java arrays multidimensional-array stack


【解决方案1】:

您说boardArray 是字符串数组的数组,而不是Stack&lt;&gt;() 的数组。

正确声明数组后,编写一个简单的嵌套循环,用new Stack&lt;&gt;()填充它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-22
    • 2012-03-11
    • 2014-10-23
    • 1970-01-01
    • 2012-12-14
    • 2017-06-21
    • 1970-01-01
    • 2014-09-01
    相关资源
    最近更新 更多