Jump to content

  • Log In with Google      Sign In   
  • Create Account

We need your help!

We need 7 developers from Canada and 18 more from Australia to help us complete a research survey. Support our site by taking a quick sponsored survey and win a chance at a $50 Amazon gift card. Click here to get started!


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


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
1 reply to this topic

#1 Code Fox   GDNet+   -  Reputation: 2755

Like
0Likes
Like

Posted 18 February 2012 - 05:27 AM

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>();
   //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) + " ");
  
}}

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(ListMaking.java:7)

What is the issue here ?

The Only Winning Move Is Not To Play  ~WOPR

Code_Fox_Sig.png


Sponsor:

#2 Angex   Members   -  Reputation: 884

Like
0Likes
Like

Posted 18 February 2012 - 09:52 AM

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!





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS