在索引处添加到ArrayList时的IndexOutOfBoundsException

Bal*_*ala 10 java arraylist indexoutofboundsexception

我得到Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0以下代码的例外.但无法理解为什么.

public class App {
    public static void main(String[] args) {
        ArrayList<String> s = new ArrayList<>();

        //Set index deliberately as 1 (not zero)
        s.add(1,"Elephant");

        System.out.println(s.size());                
    }
}
Run Code Online (Sandbox Code Playgroud)

更新

我可以使它工作,但我试图理解这些概念,所以我将声明改为下面,但也没有工作.

ArrayList<String> s = new ArrayList<>(10)
Run Code Online (Sandbox Code Playgroud)

Nav*_*kar 8

ArrayList索引从0开始(零)

您的数组列表大小为0,并且您在第一个索引处添加了String元素.如果不在第0个索引处添加元素,则无法添加下一个索引位置.哪个错了.

所以,简单地说

 s.add("Elephant");
Run Code Online (Sandbox Code Playgroud)

或者你可以

s.add(0,"Elephant");
Run Code Online (Sandbox Code Playgroud)


Soh*_*ail 6

您必须从0、1等开始依次向ArrayList添加元素。

如果您需要将元素添加到特定位置,则可以执行以下操作-

String[] strings = new String[5];
strings[1] = "Elephant";

List<String> s = Arrays.asList(strings);
System.out.println(s); 
Run Code Online (Sandbox Code Playgroud)

这将产生以下输出

[null, Elephant, null, null, null]
Run Code Online (Sandbox Code Playgroud)


Bac*_*ash 5

ArrayList是空的。用这行:

s.add(1,"Elephant");
Run Code Online (Sandbox Code Playgroud)

您正在尝试"Elephant"在不存在1ArrayList(第二个位置)的索引处添加,因此抛出IndexOutOfBoundsException

使用

s.add("Elephant");
Run Code Online (Sandbox Code Playgroud)

代替。

  • @Bala它会给你一个`IndexOutOfBoundsException`。该构造函数设置“ ArrayList”的初始“容量”,而不是“ size”。因此大小仍为0。从API中:`如果索引超出范围,则抛出IndexOutOfBoundsException(index &lt;0 || index&gt; size())` (2认同)