• Post Reply Bookmark Topic Watch Topic
  • New Topic

What is going on? new ArrayList( 10 ) throws Exception when add( 2, "something" )  RSS feed

 
Dan Bizman
Ranch Hand
Posts: 387
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I created the below ArrayList (java 1.4.2_03) and it's throwing an out of bounds exception!



What could I be doing wrong? Is there a bug in 1.4.2_03?
 
Nathaniel Stoddard
Ranch Hand
Posts: 1258
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Capacity and size are two different things. When you supply and index for a set(int, Object), the int has to be within the range of 0 to the size. Despite setting the capacity to 34, the size is still 0, and therefore you get an exception thrown.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To be more specific, the size is the number of elements currently in the list, the capacity is the number of elements the list can hold before the internally used array needs to be resized. Setting the capacity is a pure performance optimization.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!