Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Error while loading list by specified index

 
sam bats
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to load the list with index no..(I am using eclipse)

public static void main(String[] args) {

int i;
List list = new ArrayList(20);
for(i=1;i<10;i++ ){
list.add(i, new Integer(i));
System.out.println("values at index " + i +" " + list.get(i) );
}


this is throwing error like --
Exception in thread "main" java.lang.IndexOutOfBoundsException:
Index: 1,Size: 0
at java.util.ArrayList.add(Unknown Source)


can anybody help
 
Mike Noel
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the docs:

IndexOutOfBoundsException - if index is out of range (index < 0 || index > size()).


Since you haven't yet added anything to your ArrayList the size == 0. The first index you're using is 1. Since 1 > 0 you get the exception.

Usually you just add subsequent elements to the ArrayList using the add(Object) method. The add(int,Object) version is for inserting elements in the middle of the list.

_M_
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you check the API documentation for ArrayList, you'll see that the add(index, element) method throws this exception "if index is out of range (index < 0 || index > size())."

In this case, size (which is the number of elements in the list -- not its initial capacity) is 0, and you're trying to add at index 1.
 
sam bats
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks Guys !!


So the only Data structure available to store - key value pairs is --
HashMap for HashTable.
 
Mike Noel
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is also TreeMap which keeps the entries sorted.

_M_
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic