Search code examples
javaarraysstackwildcardtowers-of-hanoi

How can I instantiate an array of Stacks of type 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



Solution

  • 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);