20

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)
2
  • 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. Commented Apr 25, 2014 at 8:55
  • 1
    You are right, I see the exception at java.util.ArrayList.add. Commented Apr 25, 2014 at 8:58

10 Answers 10

14

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");
Sign up to request clarification or add additional context in comments.

Comments

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]

Comments

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.

2 Comments

How about if I change to ArrayList<String> s = new ArrayList<>(10)
@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())
2

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.

Comments

1

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

Comments

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.

1 Comment

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

Comments

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

5 Comments

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.
The OP asked specifically about ArrayList, and Arrays.asList returns a fixed-size List (stackoverflow.com/questions/2965747/…)
surely is better practice to work with interfaces, but we don't know if the OP needs the specific methods of ArrayList
@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 ArrayList does not have a single method which is not supported by AbstractList which implements List. add(index, value) is supported by List: docs.oracle.com/javase/8/docs/api/java/util/… List<String> strings = Arrays.asList(new String[10]); should be enough.
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");

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.