在索引处添加到 ArrayList 时出现 IndexOutOfBoundsException [英] IndexOutOfBoundsException when adding to ArrayList at index

查看:28
本文介绍了在索引处添加到 ArrayList 时出现 IndexOutOfBoundsException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到异常 Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0 对于下面的代码.但不明白为什么.

I get exception Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0 for the below code. But couldn't understand why.

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

更新

我可以让它工作,但我试图理解这些概念,所以我将声明更改为下面但也不起作用.

Update

I can make it work, but I am trying to understand the concepts, so I changed declaration to below but didnt work either.

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

推荐答案

ArrayList 索引从 0(零)开始

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

Your array list size is 0, and you are adding String element at 1st index. Without adding element at 0th index you can't add next index positions. Which is wrong.

所以,简单地把它变成

 s.add("Elephant");

或者你也可以

s.add(0,"Elephant");

这篇关于在索引处添加到 ArrayList 时出现 IndexOutOfBoundsException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆