Advertisement Jump to content
Sign in to follow this  

list.set() ... list.add AreThrowing Errors

This topic is 2526 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Here is the code I keep getting errors on when I uncommment the .set() and the .add() lines
// List Test
import java.util.*;
public class ListMaking {
public static void main(String args[]) {
List<String> listname = new ArrayList<String>();
System.out.println(listname.get(0) + " ");


The errors are

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.set(Unknown Source)
at ListMaking.main(

What is the issue here ?

Share this post

Link to post
Share on other sites
You can only use the "set(...)" method to replace an existing element. It will not add a new element.

The value you specify as the index must be >= 0 and < size.

NB: Size, is the number of elements in the list, not the capacity.

You cannot do this either:

ArrayList<String> list = new ArrayList<String>( 10 );

list.set(5, "Hello"); // Will throw an exception!

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using, you agree to our community Guidelines, Terms of Use, and Privacy Policy. is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!