在Stacks的ArrayList中,如果Stack是空的,为什么索引不正确?

Ian*_*ell 1 java stack arraylist indexof


我有一个Stacks的ArrayList,在其中我向其中一个Stack添加一个元素,并遍历列表打印每个Stack的索引.

然后我从前一个Stack中删除该元素,将其添加到下一个Stack,打印每个Stack的索引,并继续对ArrayList中的所有Stacks.

但是,当任何堆栈为空时,在ArrayList中获取每个堆栈的索引会有非常不寻常的行为.这是堆栈空将有正确的索引值,而该堆栈空的将有不正确的索引值.

此外,似乎如果包含元素的Stack在索引0处,则所有其他索引值将为1.如果包含元素的堆栈在任何其他索引处,则它将具有正确的索引值和所有其他索引值索引值将为0.



这是我的代码:

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
Run Code Online (Sandbox Code Playgroud)


...这里是输出(对于三个Stacks的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
Run Code Online (Sandbox Code Playgroud)


Del*_*ima 6

您获取错误索引号的原因与indexOfList中实现的方式有关.在它下面拨打电话Stack.equals().这确定了堆栈是否相等.当您list.indexOf使用空Stack 调用时,它将返回列表中第一个空堆栈的索引.