Java ArrayList 正在抛出 IndexOutOfBoundsException。为什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15017318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:13:12  来源:igfitidea点击:

Java ArrayList is throwing IndexOutOfBoundsException. Why?

javaexceptionarraylistindexoutofboundsexception

提问by Alexander

This is my current progress on a project. I am trying to implement this ArrayList stuff but file continues to trow the same exception.

这是我目前在一个项目上的进展。我正在尝试实现这个 ArrayList 的东西,但文件继续抛出相同的异常。

import java.util.*;

   public class Numerican{

      public static void main( String [] args ){

        Scanner input = new Scanner(System.in);

        ArrayList<Integer> array = new ArrayList<Integer>(10);

        int count = input.nextInt() * 2;

        while (count > 0){
           array.add( 0 );
           count = count - 1;
           array.add(count, 2);
        }

        array.add(2, input.nextInt());
        System.out.println(array.get(2));

      }
   }

It was my understanding that = new ArrayList<Integer>(10);would set the array size to 10. Did I do something wrong?

我的理解是= new ArrayList<Integer>(10);将数组大小设置为 10。我做错了什么吗?

回答by Karthik T

= new ArrayList<Integer>(10);

This line initializes the CAPACITY to 10, meaning the memory is allocated in the backend, but as far as you are concerned, the array is still empty.

这一行将 CAPACITY 初始化为 10,这意味着内存在后端分配,但就您而言,数组仍然是空的。

Javadoc-

Javadoc-

public ArrayList(int initialCapacity)
    Constructs an empty list with the specified initial capacity.

This is why the calls to addmight fail, if you try to add beyond the size of the ArrayList.

这就是为什么调用add可能会失败的原因,如果您尝试添加超出ArrayList.

p.s. remember that addfunction takes index first and then element, when using the 2 parameter variant.

ps 请记住add,当使用 2 参数变体时,函数首先采用索引,然后采用元素。

Edit:

编辑:

ArrayList has 2 different member variables, sizeand capacity. Capacity is how much memory is allocated, size is how many elements are inserted by programmer.

ArrayList 有 2 个不同的成员变量,sizecapacity。容量是分配了多少内存,大小是程序员插入了多少元素。

Here, Capacity = 10, Size = 0;

这里,容量 = 10,大小 = 0;

回答by Kanagavelu Sugumar

if the index is out of range (index < 0 || index > size()) IndexOutOfBoundsException will be thrown.
So i think you are accessing index > size() of the list.

如果索引超出范围 (index < 0 || index > size()) IndexOutOfBoundsException 将被抛出。
所以我认为您正在访问列表的 index > size() 。

size() ===> Returns the number of elements in this list.

size() ===> 返回此列表中的元素数。

array.add(2, input.nextInt()); here is the possible exception when your list size is 1...

array.add(2, input.nextInt()); 当您的列表大小为 1 时,这是可能的例外...

回答by Code-Apprentice

According to the javadocs:

根据javadocs

Constructs an empty list with the specified initial capacity.

构造一个具有指定初始容量的空列表。

Note that the ArrayList is empty(i.e. does not contain any items). The value indicates the capacityof the ArrayList which is the number of elements which can be added before more memory must be allocated.

请注意,ArrayList 是空的(即不包含任何项目)。该值表示ArrayList的容量,即在必须分配更多内存之前可以添加的元素数。

On the other hand, calling add()actually adds an item to the ArrayList. In your example, array.add( 0 );adds a 0at the end of the list and array.add(count, 2);adds a 2at index count. I suspect the problem is that countis not a valid index in your ArrayList. You should check what its value is by inserting an SOP or using a debugger.

另一方面,调用add()实际上是在 ArrayList 中添加了一个项目。在你的榜样,array.add( 0 );增加了一个0在列表的末尾,并array.add(count, 2);增加了一个2索引count。我怀疑问题在于count您的ArrayList. 您应该通过插入 SOP 或使用调试器来检查它的值是什么。

回答by Lakshmi

Hey seems like your Problem is because of the line

嘿,你的问题似乎是因为线路

array.add(count, 2); 

adds a 2 at index count

在索引计数处添加 2

For example your input size is 5 then array.add(9,2);the array size is only 1 by that time as capacity and size are two different parameters for a ArrayList. So you can use a for loop instead of while to insert your values

例如,您的输入大小为 5,那么array.add(9,2);此时数组大小仅为 1,因为容量和大小是 ArrayList 的两个不同参数。所以你可以使用 for 循环而不是 while 来插入你的值

for(int i=0; i<count;i++)
{
array.add(i,2);
}

回答by lichengwu

count maybe >= 10, maybe souce code can answer you question:

count maybe >= 10,也许源代码可以回答你的问题:

public void add(int index, E element) {
    rangeCheckForAdd(index);

    ensureCapacityInternal(size + 1);  // Increments modCount!!
    System.arraycopy(elementData, index, elementData, index + 1,
                     size - index);
    elementData[index] = element;
    size++;
}

rangeCheckForAdd():

rangeCheckForAdd():

/**
 * A version of rangeCheck used by add and addAll.
 */
private void rangeCheckForAdd(int index) {
    if (index > size || index < 0)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

回答by D. Gibbs

From my understanding of ArrayList, you need to add items to the list in a sequential index.
i.e. You cannot add an item to the 7th index position if 1 to 6 have not been filled in.

根据我对 ArrayList 的理解,您需要在顺序索引中将项目添加到列表中。
即如果没有填写1到6,则不能在第7个索引位置添加项目。

ArrayList.add(indexPosition, element);

ArrayList.add(indexPosition, element);

If you add elements to the list, starting at indexPosition 0, and increasing the indexPosition by 1 each time, it should work.

如果您将元素添加到列表中,从 indexPosition 0 开始,并且每次将 indexPosition 增加 1,它应该可以工作。

Ex.
int i = 0;
(while i < 10){
array.add(i, numberToAdd);
i++;
}

前任。
int i = 0;
(while i < 10){
array.add(i, numberToAdd);
i++;
}