简体   繁体   中英

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

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");

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

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

[null, Elephant, null, null, null]

Your ArrayList is empty. 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 .

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

Throws:

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

Use boolean add(E e) instead.

UPDATE based on the question 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. In other words, when constructed in this manner, the array list starts its life empty.

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

If you REALLY want "Elephant" at index 1, then you can add another (eg null) entry at index 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.

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

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...

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.

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

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

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");

By the way, ArrayList<String> s = new ArrayList<>(10); set the initialCapacity to 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM