Win a copy of Java Mock Exams (software) this week in the Programmer Certification (OCPJP) forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

arrayList add(int,object)

 
Jeff Gaer
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am getting
java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
at java.util.ArrayList.add(ArrayList.java:360)
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?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
What are you doing? You are supposed to be reading this tiny ad!
the new thread boost feature brings a LOT of attention to your favorite threads
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!