wood burning stoves*
The moose likes Beginning Java and the fly likes Error while loading list by specified index Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Error while loading list by specified index" Watch "Error while loading list by specified index" New topic
Author

Error while loading list by specified index

sam bats
Greenhorn

Joined: Nov 15, 2000
Posts: 6
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

Joined: Dec 15, 2005
Posts: 108
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_


Mike Noel
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

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.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
sam bats
Greenhorn

Joined: Nov 15, 2000
Posts: 6
thanks Guys !!


So the only Data structure available to store - key value pairs is --
HashMap for HashTable.
Mike Noel
Ranch Hand

Joined: Dec 15, 2005
Posts: 108
There is also TreeMap which keeps the entries sorted.

_M_
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Error while loading list by specified index
 
Similar Threads
Gradebook
LinkedList
Mock exam questions
loading list by index
How to find the smallest element in an array?