File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes arrayList add(int,object) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "arrayList add(int,object)" Watch "arrayList add(int,object)" New topic

arrayList add(int,object)

Jeff Gaer
Ranch Hand

Joined: Jun 04, 2001
Posts: 103
I am getting
java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
at java.util.ArrayList.add(
I have tried running ensureCapacity(int) first, but the array list is always size 0.
I need array like access,but want the convenience of the list interface. (i.e. i want to access items at a particular index) Is there a better solution?

Sun Certified Java Programmer Java 2<P>Jeff Gaer
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

You can do this, but first the size of the ArrayList has to be large enough. Note that size (the number of elements in the list) and capacity (the length of the array backing the list) are different. ensureCapacity() doesn't change the size. You could call list.add(null) a sufficient number of times to get you the empty slots that you need.

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link:
subject: arrayList add(int,object)
It's not a secret anymore!