java - 在索引处添加到 ArrayList 时出现 IndexOutOfBoundsException

标签 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());                
    }
}

更新

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

ArrayList<String> s = new ArrayList<>(10)

最佳答案

ArrayList索引从0(零)开始

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

所以,简单地把它变成

 s.add("Elephant");

或者你可以

s.add(0,"Elephant");

关于java - 在索引处添加到 ArrayList 时出现 IndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23288439/

相关文章:

java - 查找 ArrayList 中使用最多和最少的字符串(不使用 Hashmap)

java - 如何在Java中创建字符和动态ArrayList的映射

java - 列表循环JavaFx

通过 fgets() 读取文件时检查错误

java - jXLS 创建了文档 : No calculating from the start

java - 我类(class)的数据为空?

Java 和类型删除

java - 无法从循环外部找到循环中的 int

java - 如何通过交换列表中的其他数据中心来将本地数据中心放在列表中的第一位?

java - 从 BufferedImage 渲染 Sprite 时出现问题