【问题标题】:How can I instantiate an array of Stacks of type int?如何实例化 int 类型的 Stacks 数组?
【发布时间】:2013-03-09 22:26:50
【问题描述】:


我正在尝试创建一个堆栈数组,其中数组中的每个堆栈都是int 类型。

如果我这样创建数组:Stack<Integer>[] numbers = new Stack<Integer>[3];,则会出现编译错误“Cannot create a generic array of Stack<Integer>”。因此,我尝试使用通配符类型而不是 Integer 创建堆栈数组,然后 not 会出现此错误。

但是,如果我尝试将int 推入堆栈之一(通配符“?”类型),如下所示:this.numbers[stackIndex].push(i);,则会出现编译错误“The method push(capture#1-of ?) in the type Stack<capture#1-of ?> is not applicable for the arguments (int)”。

那么,我怎样才能正确地实例化int 类型的堆栈数组呢?截至目前,我无法在这些堆栈上执行推送/弹出操作......


我的推理是尝试对河内塔游戏进行编程。我希望这三个杆中的每一个都是int 类型的Stack,每个环都表示为int,并且三个杆一起包含为三个堆栈的数组。


这是一些示例代码:
import java.util.Stack;

public class StackTest {

    Stack<?>[] numbers;

    public StackTest(int stackLength) {
        this.numbers = new Stack<?>[stackLength];
    }

    public void fillStack(int stackIndex, int numRings) {
        for (int i = numRings; i >= 0; i--) {

            // this statement has a compile error!
            this.numbers[stackIndex].push(i);
        }
    }

    public static void main(String[] args) {
        int numberOfRods = 3;
        StackTest obj = new StackTest(numberOfRods);

        int rodNumber = 0, numberOfRings = 4;
        obj.fillStack(rodNumber, numberOfRings);
    }
} // end of StackTest


【问题讨论】:

    标签: java arrays stack wildcard towers-of-hanoi


    【解决方案1】:

    它必须是原始的Stack[],或者您可以使用List&lt;Stack&lt;YourClass&gt;&gt; lstStack = new ArrayList&lt;Stack&lt;YourClass&gt;&gt;()

    在这种情况下,我更愿意使用

    List<Stack<Integer>> lstStack = new ArrayList<Stack<Integer>>(stackLength);
    

    【讨论】:

    • 感谢您的快速回复!但是,当我将其更改为原始 Stack[] 时,我收到警告“Stack is a raw type. References to generic type Stack&lt;E&gt; should be parameterized”。有没有办法避免这个警告?
    • @IanCampbell 是的,使用第二种方式。
    • 再次感谢@Luiggi,但是当我尝试第二种方式时,我得到了编译错误“The type List is not generic; it cannot be parameterized with arguments &lt;Stack&lt;Integer&gt;&gt;"
    • @IanCampbell 你确定你在使用java.util.List
    【解决方案2】:

    一种解决方案可能是:

    public class StackInteger extends Stack<Integer> {
    }
    

    然后:

    StackInteger[] numbers = new StackInteger[3];
    

    甚至:

    Stack<Integer>[] numbers = new StackInteger[3];
    

    【讨论】:

    • 谢谢@sp00m,这很有趣,但是当我这样做时,我在类声明中收到警告“The serializable class StackInteger does not declare a static final serialVersionUID field of type long”。
    【解决方案3】:

    我猜你应该推送Integer而不是int

    this.numbers[stackIndex].push(Integer.valueOf(i));
    

    【讨论】:

    • 我喜欢这个解决方案,但是当我将第 5 行更改为 Stack&lt;Integer&gt; numbers; 并将第 8 行更改为 this.numbers = new Stack[stackLength]; 时,我收到警告“Type safety: The expression of type Stack[] needs unchecked conversion to conform to Stack&lt;Integer&gt;[]”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-09
    • 2018-11-13
    • 2018-11-02
    • 1970-01-01
    相关资源
    最近更新 更多