1

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!

5 Answers 5

2

You don't use set to add to an ArrayList you use it to overwrite an existing element.

problems.set(1, p); //Overwrite the element at position 1 

You use add

problems.add(p); 

will add it at the end

problems.add(1, p);

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

problems.add(ArrayList.size(), p); //Works the same as problems.add(p);
Sign up to request clarification or add additional context in comments.

Comments

2

ArrayList#set()

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

size() returns number of elements in the array list, not the capacity.

Comments

1

When you write ArrayList<Problem> problems = new ArrayList <Problem>( 100 );, you only tell Java that you think you are going to use that kind of capacity (which optimises the size of the underlying array) but the list still has a size of 0.

You need to use add():

problems.add(p);

will add p in the first position.

List<Problem> problems = new ArrayList <Problem>();
Problem p = new Problem ();
p.setProblemName( "Some text" );

problems.add(p);

Problem p2 = problems.get(0); //p2 == p

Comments

0

you should write this instead:

problems.add(0, p);

You haven't any 0th member that you want to insert p into 1st place!

1 Comment

Set won't work. The ArrayList has no elements yet so Size = 0. Set throws and IndexOfOutBoundsException if the index is >= size.
-1

try

problems.set(0, p); 

the first position in an array is always 0.

edit you should be using the .add() method to add an object to the array though

2 Comments

when I set it to 0, I get this error: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
Set will not work if there isn't an element in the list already. He has to use add. Set fails in index < 0 || index >= size. With a size=0 set always fails.

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.