我有一个堆栈的ArrayList,其中我添加一个元素到一个堆栈,并遍历列表打印每个堆栈的索引。
然后,我从前一个堆栈中删除该元素,将其添加到下一个堆栈,打印每个堆栈的索引,然后继续处理ArrayList中的所有堆栈。
但是,当任何堆栈为空时,在获取ArrayList中每个堆栈的索引时会出现非常不寻常的行为。这是不空堆栈将有正确的索引值,而栈是是空将有不正确的索引值。
此外,如果包含一个或多个元素的堆栈位于索引0处,则所有其他索引值将为1.如果包含元素的堆栈位于任何其他索引处,则它将具有正确的索引值和所有其他指数值将是0
在堆栈的ArrayList中,如果堆栈为空,为什么索引不正确?
这里是我的代码:
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
...这里是输出(三栈的ArrayList):
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
感谢@DeltaLima的帮助,那么如何才能实现具有空栈的“正常”索引行为? – 2013-03-23 20:41:31
那么......没有关于你想要达到的东西的更多知识,这有点难以回答。我想知道列表的选择是否正确。这里不是一个简单的数组吗? – DeltaLima 2013-03-23 20:48:38
感谢@DeltaLima,我曾尝试使用堆栈的数组之前,但有几个错误(请参阅:http://stackoverflow.com/questions/15530118/how-can-i-instantiate-an-array-of-stacks- of-type/15530140#comment22001592_15530140)。我的目的是创建一个合适的结构来解决河内塔问题。 – 2013-03-23 20:56:38