我正在尝试创建一个堆栈数组,其中数组中的每个堆栈的类型为 int
。
如果我像这样创建数组: Stack<Integer>[] numbers = new Stack<Integer>[3];
,出现编译错误“Cannot create a generic array of Stack<Integer>
”。因此,我尝试使用通配符类型而不是 Integer
创建堆栈数组。 ,然后它不会出现此错误。
但是,如果我随后尝试推送 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
类型的 Stacks 数组?截至目前,我无法在这些堆栈上执行推送/弹出操作...
我的推理是尝试编写汉诺塔游戏。我希望这三个杆中的每一个都是
Stack
类型 int
,每个环都表示为 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
最佳答案
它必须是原始的 Stack[]
或者您可以使用List<Stack<YourClass>> lstStack = new ArrayList<Stack<YourClass>>()
.
在这种情况下,我更愿意使用
List<Stack<Integer>> lstStack = new ArrayList<Stack<Integer>>(stackLength);
关于java - 如何实例化 int 类型的 Stack 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15530118/