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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23288439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:41:20  来源:igfitidea点击:

IndexOutOfBoundsException when adding to ArrayList at index

javaarraylistindexoutofboundsexception

提问by Bala

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

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

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)

采纳答案by Naveen Kumar Alonekar

ArrayList index starts from 0(Zero)

ArrayList 索引从 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.

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

So, Simply make it as

所以,简单地把它作为

 s.add("Elephant");

Or you can

或者你可以

s.add(0,"Elephant");

回答by BackSlash

Your ArrayListis empty. With this line:

你的ArrayList是空的。有了这条线:

s.add(1,"Elephant");

You are trying to add "Elephant"at index 1of the ArrayList(second position), which doesn't exist, so it throws a IndexOutOfBoundsException.

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

Use

s.add("Elephant");

instead.

反而。

回答by Abimaran Kugathasan

add(int index, E element)API says, Your array list has zero size, and you are adding an element to 1st index

add(int index, E element)API 说,您的数组列表大小为零,并且您正在向第一个索引添加一个元素

Throws:

IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())

抛出:

IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())

Use boolean add(E e)instead.

使用boolean add(E e)来代替。

UPDATEbased on the question update

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<String> s = new ArrayList<>(10)

When you call new ArrayList<Integer>(10), you are setting the list's initial capacity to 10, not its size. In other words, when constructed in this manner, the array list starts its life empty.

当您调用 时new ArrayList<Integer>(10),您将列表的初始容量设置为 10,而不是其大小。换句话说,以这种方式构造时,数组列表的生命周期是空的。

回答by Denis Kulagin

ArrayListis not self-expandable. To add an item at index 1, you should have element #0.

ArrayList不可自扩展。要在索引 1 处添加项目,您应该拥有元素 #0。

回答by jedison

If you REALLY want "Elephant" at index 1, then you can add another (e.g. null) entry at index 0.

如果您真的想要索引 1 处的“大象”,那么您可以在索引 0 处添加另一个(例如空)条目。

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

    s.add(null);
    s.add("Elephant");

    System.out.println(s.size());                
  }
}

Or change the calls to .addto specify null at index 0 and elephant at index 1.

或者更改调用以.add在索引 0 处指定 null 并在索引 1 处指定大象。

回答by Sohail

You must add elements to ArrayList serially, starting from 0, 1 and so on.

您必须按顺序向 ArrayList 添加元素,从 0、1 等开始。

If you need to add elements to specific position you can do the following -

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

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

List<String> s = Arrays.asList(strings);
System.out.println(s); 

This will produce the sollowing output

这将产生 solowing 输出

[null, Elephant, null, null, null]

回答by veeru

Don't add index as 1 directly in list If you want to add value in list add it like this s.add("Elephant"); By default list size is 0 If you will add any elements in list, size will increased automatically you cant add directly in list 1st index. //s.add(0, "Elephant");

不要在列表中直接将索引添加为 1 如果要在列表中添加值,请像这样添加 s.add("Elephant"); 默认列表大小为 0 如果您要在列表中添加任何元素,大小将自动增加,您不能直接添加到列表第一个索引中。//s.add(0, "大象");

回答by David Miguel

For Android:

对于安卓:

If you need to use a list that is going to have a lot of gaps it is better to use SparseArrayin terms of memory (an ArrayListwould have lots of nullentries).

如果您需要使用一个有很多空白的列表,最好SparseArray在内存方面使用(一个ArrayList会有很多null条目)。

Example of use:

使用示例:

SparseArray<String> list = new SparseArray<>();
list.put(99, "string1");
list.put(23, "string2");
list.put(45, "string3");
  • Use list.append()if you add sequential keys, such as 1, 2, 3, 5, 7, 11, 13...
  • Use list.put()if you add non-sequential keys, such as 100, 23, 45, 277, 42...
  • 使用list.append()如果添加顺序键,如1,2,3,5,7,11,13 ...
  • 使用list.put()如果添加非连续的键,如100,23,45,277,42 ...

If your list is going to have more than hundreds of items is better to use HashMap, since lookups require a binary search and adds and removes require inserting and deleting entries in the array.

如果您的列表将有超过数百个项目,最好使用HashMap,因为查找需要二分搜索,而添加和删除需要在数组中插入和删除条目。

回答by Bruno F

You can initialize the size (not the capacity) of an ArrayList in this way:

您可以通过这种方式初始化 ArrayList 的大小(而不是容量):

ArrayList<T> list = new ArrayList<T>(Arrays.asList(new T[size]));

in your case:

在你的情况下:

ArrayList<String> s = new ArrayList<String>(Arrays.asList(new String[10]));

this creates an ArrayList with 10 null elements, so you can add elements in random order within the size (index 0-9).

这将创建一个包含 10 个空元素的 ArrayList,因此您可以在大小(索引 0-9)内以随机顺序添加元素。