I have an ArrayList of Stacks, in which I add an element to one of the Stacks and iterate through the list printing the index of each Stack.
Then I remove the element from the previous Stack, add it to the next Stack, print the index of each Stack, and continue this for all Stacks in the ArrayList.
However, when any of the Stacks are empty there is very unusual behavior in getting the index of each Stack in the ArrayList. The Stack that is not empty will have the correct index value, whereas the Stacks that are empty will have incorrect index values.
Furthermore, it seems that if the Stack containing an element(s) is at index 0 all other index values will be 1. If the Stack containing an element(s) is at any other index it will have the correct index value and all other index values will be 0.
Here is my code:
import java.util.List;
import java.util.Stack;
import java.util.ArrayList;
public class ListOfStacks {
// instance variables:
List<Stack<Integer>> stacks;
private static final int NUMBER_OF_STACKS = 3;
// constructor:
ListOfStacks() {
this.stacks = new ArrayList<Stack<Integer>>(NUMBER_OF_STACKS);
// adding the stacks to the list here:
for (int i = 0; i < NUMBER_OF_STACKS; i++) {
this.stacks.add(new Stack<Integer>());
}
}
// instance methods:
void addElement(int stackIndex, int element) {
this.stacks.get(stackIndex).add(element);
}
void removeElement(int stackIndex) {
this.stacks.get(stackIndex).pop();
}
void printIndexes(int stackIndex, int element) {
System.out.printf("The stack at index %d now contains %d" +
"(the other stacks are empty):%n", stackIndex, element);
for (Stack<Integer> stack : this.stacks) {
System.out.printf("index %d%n", this.stacks.indexOf(stack));
}
System.out.println();
}
// main method:
public static void main(String[] args) {
ListOfStacks list = new ListOfStacks();
int index = 0, number = 5;
// adding the number 5 to the stack at index 0:
list.addElement(index, number);
list.printIndexes(index, number);
// now removing that element, and adding it to the stack at index 1:
list.removeElement(index++);
list.addElement(index, number);
list.printIndexes(index, number);
// now removing that element, and adding it to the stack at index 2:
list.removeElement(index++);
list.addElement(index, number);
list.printIndexes(index, number);
}
} // end of ListOfStacks
...and here is the output (for an ArrayList of three Stacks):
The stack at index 0 now contains 5 (the other stacks are empty):
index 0
index 1
index 1
The stack at index 1 now contains 5 (the other stacks are empty):
index 0
index 1
index 0
The stack at index 2 now contains 5 (the other stacks are empty):
index 0
index 0
index 2