• 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:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

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_
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!