Java ArrayList抛出了IndexOutOfBoundsException.为什么?

Ale*_*der 1 java exception arraylist indexoutofboundsexception

这是我目前在项目上取得的进展.我试图实现这个ArrayList的东西,但文件继续trow相同的异常.

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));

      }
   }
Run Code Online (Sandbox Code Playgroud)

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

Kar*_*k T 7

= new ArrayList<Integer>(10);
Run Code Online (Sandbox Code Playgroud)

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

Javadoc -

public ArrayList(int initialCapacity)
    Constructs an empty list with the specified initial capacity.
Run Code Online (Sandbox Code Playgroud)

这就是为什么调用add可能会失败,如果你试图添加超出的大小ArrayList.

ps记住add,当使用2参数变量时,函数先取索引然后取元素.

编辑:

ArrayList有2个不同的成员变量,大小容量.容量是分配的内存量,大小是程序员插入的元素数量.

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