如何实例化int类型的Stacks数组? [英] How can I instantiate an array of Stacks of type int?
问题描述
我正在尝试创建一个堆栈数组,其中该数组中的每个堆栈的类型为 int
。
如果我这样创建数组: Stack< Integer> []数字=新的Stack< Integer> [3];
  ;,会出现编译错误 无法创建Stack
的通用数组。因此,我尝试使用通配符类型而不是 Integer
创建堆栈数组, 然后 not 没有此错误。
但是,如果我尝试将 int
推入堆栈之一(通配符 ?
类型),就像这样: this.numbers [stackIndex] .push(i);
  ;,有编译错误 类型Stack< capture#1-of?>中的方法push(capture#1-of?)不适用于参数(int)
。
那么,如何正确实例化 int
类型的堆栈数组?到目前为止,我无法在这些堆栈上执行推入/弹出操作...
我的理由是尝试对Tower进行编程河内游戏。我希望这三根棒都成为
int
类型的 Stack
,每个环都表示为 int
,并将这三个标尺组合在一起,作为三个堆栈的数组。 这是一些示例代码:
I am trying to create an array of stacks, in which each stack within the array is of type int
.
If I create the array like this: Stack<Integer>[] numbers = new Stack<Integer>[3];
, there is the compile error "Cannot create a generic array of Stack<Integer>
". So, I am trying to create the array of Stacks with the wildcard type instead of Integer
, and it then does not have this error.
However, if I then try to push an int
into one of the stacks (of wildcard "?
" type) like this: this.numbers[stackIndex].push(i);
, there is the compile error "The method push(capture#1-of ?) in the type Stack<capture#1-of ?> is not applicable for the arguments (int)
".
So, how can I properly instantiate an array of Stacks of type int
? As of now I am not able to perform push/pop operations on these Stacks...
My reasoning in this is an attempt to program the Tower of Hanoi game. I wanted each of the three rods to be a
Stack
of type int
, each ring to be represented as an int
, and the three rods together to be contained as an array of the three Stacks.
Here is some example code:
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>>()
。
It has to be a raw Stack[]
or you can use List<Stack<YourClass>> lstStack = new ArrayList<Stack<YourClass>>()
.
在这种情况下,我宁愿使用
In this case, I would prefer to use
List<Stack<Integer>> lstStack = new ArrayList<Stack<Integer>>(stackLength);
这篇关于如何实例化int类型的Stacks数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!