• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

ArrayList Question

 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
import java.util.*;

class test {
public static void main(String args[]) {
List list=new ArrayList(5);
list.add(1,new Integer(1));
list.add(2,new Integer(2));
list.add(3,new Integer(3));
Object o=(Integer)list.get(0);
System.out.println(o);
}
}
Why it compiles error saying java.lang.IndexOutOfBoundsException?
I know List are something like array but
when array are initialized,it will be automatically given a default value.
Then,what about the subclasses of List Interface.
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
IndexOutOfBoundException is thrown when you give an insert index that is bigger than the current size of the list.
You insert the first element at index 1 when the list is empty (size=0), hence the exception...
If you insert at index 0, then 1, then 2 it is ok... Try it...
HIH
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
First of all, the compile for this code is OK. IndexOutOfBoundsException is a RuntimeException. Only when you run that code, it will generate this exception. You cannot add(1, new Integer(1)); when the size of that array is 0. Method public void add(int index, Object element) in ArrayList checks it.
Zheng Xu
[ February 05, 2002: Message edited by: Zheng Xu ]
[ February 05, 2002: Message edited by: Zheng Xu ]
 
Did you miss me? Did you miss this tiny ad?
Clean our rivers and oceans from home
https://www.kickstarter.com/projects/paulwheaton/willow-feeders
reply
    Bookmark Topic Watch Topic
  • New Topic