18

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)
Bala
  • 11,068
  • 19
  • 67
  • 120
  • 2
    If you read your stack trace carefully, you'll see the error is when you are adding, not when requesting size. I've edited your title accordingly. – Duncan Jones Apr 25 '14 at 08:55
  • 1
    You are right, I see the exception `at java.util.ArrayList.add`. – Bala Apr 25 '14 at 08:58

10 Answers10

12

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");
Naveen Kumar Alone
  • 7,536
  • 5
  • 36
  • 57
7

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]
Sohail
  • 4,506
  • 2
  • 38
  • 42
5

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.

BackSlash
  • 21,927
  • 22
  • 96
  • 136
  • 1
    How about if I change to `ArrayList s = new ArrayList<>(10)` – Bala Apr 25 '14 at 09:02
  • 3
    @Bala It will give you an `IndexOutOfBoundsException`. That constructor sets the initial **capacity** of the `ArrayList`, not the **size**. So the size is still 0. And from APIs: `Throws IndexOutOfBoundsException if the index is out of range (index < 0 || index > size())` – BackSlash Apr 25 '14 at 09:05
1

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.

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
  • This is where I am getting dis-oriented. My index `1` is not less than zero and size is `1` so index is not greater than size. – Bala Apr 25 '14 at 09:10
1

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

Denis Kulagin
  • 8,472
  • 17
  • 60
  • 129
1

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

jedison
  • 908
  • 6
  • 15
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.

David Miguel
  • 12,154
  • 3
  • 66
  • 68
1

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

Bruno F
  • 31
  • 3
  • Arrays.asList(new String[10]) - already returns a list. so wrapping it up is kind of useless. the variable s should be primitive type List, not of the implementation ArrayList. – Bojan Petkovic Sep 05 '18 at 16:29
  • The OP asked specifically about ArrayList, and Arrays.asList returns a fixed-size List (https://stackoverflow.com/questions/2965747/why-do-i-get-an-unsupportedoperationexception-when-trying-to-remove-an-element-f) – Bruno F Sep 06 '18 at 07:04
  • surely is better practice to work with interfaces, but we don't know if the OP needs the specific methods of ArrayList – Bruno F Sep 06 '18 at 07:16
  • @Bojan Petkovic, Arrays.asList(new String[10]) will return an AbstractList. The operation add(index, value) is not supported on AbstractList. So it needs to be wrapped (by a non-abstract type of List implementation). – imnd_neel May 08 '20 at 09:46
  • @imnd_neel ArrayList does not have a single method which is not supported by AbstractList which implements List. add(index, value) is supported by List: https://docs.oracle.com/javase/8/docs/api/java/util/List.html#add-int-E- List strings = Arrays.asList(new String[10]); should be enough. – Bojan Petkovic Jul 13 '20 at 20:21
0

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

veeru
  • 91
  • 1
  • 1
  • 5
0

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.

Simas Joneliunas
  • 2,890
  • 20
  • 28
  • 35
Dudadi
  • 31
  • 2