Sign in to follow this  
RLS0812

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

Recommended Posts

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

}}[/code]

The errors are

[code]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(ListMaking.java:7)[/code]

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:

[CODE]
ArrayList<String> list = new ArrayList<String>( 10 );

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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this