I get exception Exception in thread \"main\" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
for the below code. But couldn\'t understand why.
ArrayList is not self-expandable. To add an item at index 1, you should have element #0.
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");
list.append()
if you add sequential keys, such as 1, 2, 3, 5, 7, 11, 13...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.
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.
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.
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.
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.