I have this array:
ArrayList<Problem> problems = new ArrayList <Problem>( 100 );
then I try to make an object to put in it:
Problem p = new Problem ();
p.setProblemName( "Some text" );
Then I try to add the object to the array:
problems.set(1, p);
But at this point the system throws a runtime exception:
03-12 18:58:04.573: E/AndroidRuntime(813): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0
But if I increase the initial size of the array to 100. Why does this error happen? It seems this is super straight forward.
Thanks!
You don’t use
setto add to anArrayListyou use it to overwrite an existing element.You use
addwill add it at the end
will add it at index 1, this will throw an IndexOutOfBoundsException for
index < 0 or index >
ArrayList.size(). Which will be the case on the first attempt for an add.Also just for your knowledge