IndexOutOfBoundsException异常索引增加ArrayList的时候 [英] IndexOutOfBoundsException when adding to ArrayList at index

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

问题描述

我得到异常异常线程mainjava.lang.IndexOutOfBoundsException:指数:1,大小:0 为低于code。但不明白为什么。

 公共类应用{
    公共静态无效的主要(字串[] args){
        ArrayList的<串GT; S =新的ArrayList<>();        // SET指数故意为1(不为零)
        s.add(1,大象);        的System.out.println(s.size());
    }
}

更新

我可以让它工作,但我想了解的概念,所以我改变声明以下,但没有工作无论是。

 的ArrayList<串GT; S =新的ArrayList<>(10)


解决方案

数组索引开始从0(零)

您数组列表的大小为0,而你在第一个指数添加字符串元素。如果没有在第0个指标中加入元素,您不能添加一个索引位置。这是不对的。

所以,简单地使其为

  s.add(大象);

或者你可以

  s.add(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)

解决方案

Array index starts from 0(Zero)

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.

So, Simply make it as

 s.add("Elephant");

Or you can

s.add(0,"Elephant");

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

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