【问题标题】:Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 8, Size: 0 at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:665) [duplicate]线程“主”java.lang.IndexOutOfBoundsException 中的异常:索引:8,大小:0 在 java.util.ArrayList.rangeCheckForAdd(ArrayList.java:665) [重复]
【发布时间】:2021-07-04 15:16:22
【问题描述】:

我试图解决一个问题,它被描述为 -> 给定一个数组 A,为数组中的每个元素 A[i] 找到下一个更大的元素 G[i]。元素 A[i] 的下一个更大元素是数组 A 中 A[i] 右侧的第一个更大元素。对于不存在更大元素的元素,将下一个更大元素视为 -1。

public class Solution {
    public ArrayList<Integer> nextGreater(ArrayList<Integer> A) {
       Stack<Integer> stk = new Stack<>();
       if (A.size() == 1)
        {
            ArrayList<Integer> ans= new ArrayList<>();
            ans.add(0,-1);
            return ans;
        }
       ArrayList<Integer> ans= new ArrayList<>(A.size());
       ans.add(A.size()-1,-1); //error ->Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 8, Size: 0
       stk.push(0);
       for(int i=1;i<A.size()-1;i++){
               while(!stk.isEmpty()&&A.get(i)>A.get(stk.peek())){
                   ans.add(stk.pop(),A.get(i));
                //   stk.pop();
               }
               stk.push(i);
           }
       return ans;
    }
}

但是在解决这个问题时,我不明白为什么在数组列表中的位置 A.size()-1 添加 -1 时出现错误,其中 A : [ 34, 35, 27, 42, 5, 28, 39, 20, 28]

【问题讨论】:

    标签: java arraylist runtime-error indexoutofboundsexception


    【解决方案1】:

    A.size()0,因为列表中还没有元素。数组应该用一个起始值来初始化,而不是列表(ArrayLists)。 您应该在没有容量的情况下初始化 ArrayList: ArrayList&lt;Integer&gt; ans= new ArrayList&lt;&gt;();

    那么你可以简单 ans.add(-1);

    或者更好的是,您可以在方法的最后添加-1

    【讨论】:

      【解决方案2】:

      ArrayList 构造函数用于初始容量,它不会用元素填充 ArrayList,在插入或添加元素之前大小为 0。

      【讨论】:

      • 哦,对了……理解我的错误……非常感谢先生!!
      猜你喜欢
      • 2016-01-12
      • 1970-01-01
      • 2013-11-22
      • 1970-01-01
      • 1970-01-01
      • 2016-12-28
      • 1970-01-01
      • 1970-01-01
      • 2020-08-30
      相关资源
      最近更新 更多