简体   繁体   English

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

[英]IndexOutOfBoundsException when adding to ArrayList at index

I get exception Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0 for the below code.对于以下代码Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0得到异常Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0 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 index starts from 0(Zero) ArrayList 索引从 0(零)开始

Your array list size is 0, and you are adding String element at 1st index.您的数组列表大小为 0,并且您在第一个索引处添加 String 元素。 Without adding element at 0th index you can't add next index positions.如果不在第 0 个索引处添加元素,则无法添加下一个索引位置。 Which is wrong.这是错误的。

So, Simply make it as所以,简单地把它作为

 s.add("Elephant");

Or you can或者你可以

s.add(0,"Elephant");

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]

Your ArrayList is empty.你的ArrayList是空的。 With this line:有了这条线:

s.add(1,"Elephant");

You are trying to add "Elephant" at index 1 of the ArrayList (second position), which doesn't exist, so it throws a IndexOutOfBoundsException .您正在尝试在不存在的ArrayList (第二个位置)的索引1处添加"Elephant" ,因此它会抛出一个IndexOutOfBoundsException

Use

s.add("Elephant");

instead.反而。

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

Use boolean add(E e) instead.请改用boolean add(E e)

UPDATE based 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)

When you call new ArrayList<Integer>(10) , you are setting the list's initial capacity to 10, not its size.当您调用new ArrayList<Integer>(10) ,您将列表的初始容量设置为 10,而不是其大小。 In other words, when constructed in this manner, the array list starts its life empty.换句话说,以这种方式构造时,数组列表的生命周期是空的。

ArrayList is not self-expandable. ArrayList不可自扩展。 To add an item at index 1, you should have element #0.要在索引 1 处添加项目,您应该拥有元素 #0。

If you REALLY want "Elephant" at index 1, then you can add another (eg 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 .add to specify null at index 0 and elephant at index 1.或者将调用更改为.add以在索引 0 处指定 null 并在索引 1 处指定大象。

For Android:对于安卓:

If you need to use a list that is going to have a lot of gaps it is better to use SparseArray in terms of memory (an ArrayList would have lots of null entries).如果您需要使用一个有很多间隙的列表,最好在内存方面使用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...如果添加顺序键,例如list.append()请使用list.append()
  • Use list.put() if you add non-sequential keys, such as 100, 23, 45, 277, 42...如果添加非顺序键,例如list.put()请使用list.put()

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 ,因为查找需要二分搜索,而添加和删除需要在数组中插入和删除条目。

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)内以随机顺序添加元素。

Don't add index as 1 directly in list If you want to add value in list add it like this s.add("Elephant");不要在列表中直接将索引添加为 1 如果要在列表中添加值,请像这样添加 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.默认列表大小为 0 如果您要在列表中添加任何元素,大小将自动增加,您不能直接添加到列表第一个索引中。 //s.add(0, "Elephant"); //s.add(0, "大象");

By the way, ArrayList<String> s = new ArrayList<>(10);顺便说一下, ArrayList<String> s = new ArrayList<>(10); set the initialCapacity to 10.将初始容量设置为 10。

Since the capacity of Arraylist is adjustable, it only makes the java knows the approximate capacity and try to avoid the performance loss caused by the capacity expansion.由于Arraylist的容量是可调的,它只是让java知道大概的容量,尽量避免扩容带来的性能损失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 IndexOutOfBoundsException at Index: 4, Size: 4 将元素添加到 ArrayList 时 - IndexOutOfBoundsException at Index: 4, Size: 4 when adding elements to an ArrayList 添加到ArrayList时出现IndexOutOfBoundsException - IndexOutOfBoundsException when adding to ArrayList arraylist indexoutofboundsexception索引0大小0 - arraylist indexoutofboundsexception index 0 size 0 使用arrayList时IndexOutOfBoundsException - IndexOutOfBoundsException when working with arrayList 递增 ArrayList 时出现 IndexOutOfBoundsException - IndexOutOfBoundsException When Incrementing ArrayList 使用嵌套 while 循环添加到 ArrayList 时出现 IndexOutOfBoundsException - IndexOutOfBoundsException when adding to ArrayList using nested while loops Java ArrayList IndexOutOfBoundsException索引:1,大小:1 - Java ArrayList IndexOutOfBoundsException Index: 1, Size: 1 添加到arraylist中的列表时出现IndexOutOfBoundsException - IndexOutOfBoundsException while adding to a list in an arraylist 通过LiveData观察器将项目添加到特定索引时出现IndexOutOfBoundsException - IndexOutOfBoundsException when adding items to specific index through LiveData observer 删除ArrayList元素时出现IndexOutOfBoundsException - IndexOutOfBoundsException when removing ArrayList element
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM