java.lang.ArrayIndexOutOfBoundsException 的原因

Reason for java.lang.ArrayIndexOutOfBoundsException

知道这行有什么问题吗? outStr[i]=(String) s.pop();

import java.util.ArrayList;
import java.util.Scanner;

public class StringWordReverse {

    public String[] StringToWord(){
        Scanner sc = new Scanner(System.in);
        sc.useDelimiter(" ");
        ArrayList<String> wordList= new ArrayList<String>();
        String sc_in= sc.nextLine();
        String[] sc_split=sc_in.split(" +");
        for (int i=0; i<sc_split.length; i++){
            wordList.add(sc_split[i]);
        }

        String[] stringArr= new String[wordList.size()];
        for (int i=0; i<wordList.size(); i++){
            stringArr[i]= wordList.get(i);
        }
        return stringArr;


    }

    public String[] reverseWords(String[] words){
        Stack<String> s= new Stack<String>();
        String[] outStr=new String[words.length];
        for (int i=0; i<words.length; i++){
            s.push(words[i]);
        }
        for (int i=0; i<words.length; i++){
            System.out.println(s.stackSize());
            outStr[i]=(String) s.pop();
        }

        return outStr;  

    }

    public static void main(String[] argc){
        StringWordReverse swr = new StringWordReverse();


        String[] inputWords= swr.StringToWord();
        String[] outputWords=swr.reverseWords(inputWords);
        for (int i=0; i<outputWords.length;i++)
            System.out.println(outputWords[i]);


        return;
    }



}

这是我的堆栈 class:

    import java.util.ArrayList;

public class Stack<E> {
    private ArrayList<E> s = new ArrayList<E>();
    private static int size=0;

    public void push(E item){
        s.add(item);
        size++;
        return;
    }

    public E pop(){
        size--;
        return s.remove(size-1);

    }

    public int stackSize(){
        return size;
    }


}

这是我收到的错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    at java.util.ArrayList.elementData(ArrayList.java:400)
    at java.util.ArrayList.remove(ArrayList.java:477)
    at XYZ.Stack.pop(Stack.java:16)
    at XYZ.StringWordReverse.reverseWords(StringWordReverse.java:35)
    at XYZ.StringWordReverse.main(StringWordReverse.java:47)

您正在减小尺寸变量,然后您使用相同的尺寸变量从堆栈中取出项目。因此,当您调用 pop 并留下一项时,您将大小减小为 0,然后尝试删除位置 -1 的项目。

既然列表中已有一个大小变量,为什么还要保留自己的大小变量?

这段代码中有些错误:

  • 您使用原始类型而不是泛型。让编译器帮助您解决(大多数)运行时类型错误:Stack<String> stack = new Stack<>()

  • Stack.pop 中,您永远不会检查是否有要弹出的元素。你应该测试它并抛出一个异常,例如 NoSuchElementException 如果堆栈是空的。

  • Stack.pop 中,您正在递减大小,然后删除项目 size - 1,因此您基本上递减了两次。这应该是:s.remove(--size);

尝试更改这部分代码:

public E pop(){
    size--;
    return s.remove(size-1);
}

对此:

public E pop(){
    return s.remove(size--);
}

那是错误。