Win a copy of The Journey To Enterprise Agility this week in the Agile and Other Processes forum! And see the welcome thread for 20% off.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

Error while loading list by specified index  RSS feed

 
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
 
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_
 
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_
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!