问题
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
回答1:
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);
回答2:
One solution could be:
public class StackInteger extends Stack<Integer> {
}
And then:
StackInteger[] numbers = new StackInteger[3];
Or even:
Stack<Integer>[] numbers = new StackInteger[3];
回答3:
My guess is that you should push an Integer
rather than an int
:
this.numbers[stackIndex].push(Integer.valueOf(i));
来源:https://stackoverflow.com/questions/15530118/how-can-i-instantiate-an-array-of-stacks-of-type-int