Skip to main content

Bug in ArrayList?

1 reply [Last post]
Joined: 2006-11-06

If you try this tiny program:

<br />
	ArrayList list = new ArrayList();<br />
	for( int i = 0; i < 20; i+=2)<br />
	{<br />
		list.ensureCapacity( i );<br />
		list.add( i, "test" + i );<br />
	}<br />
	System.out.println( "list = " + list );<br />

You get an IndexOutOfBoundsException. Why?

If you change the "i+=2" by "i++", you don't get an exception. Is this a bug in ArrayList or just misunderstanding from my side?



Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2006-12-18

capacity != size

The indices at which you can insert are bounded by [0, size()]. What [i]ensureCapacity(int n)[/i] does is guarantee you there will be no need for the datastructure to stretch to hold [i]n[/i] objects.