This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
I have an arrayList, and I'm adding objects to it at various positions. I use the arrayList ensureCapacity() to make sure the arrayList can accept a large subscript - but it doesnt seem to work? heres the code...
I've also tried to add() - not just trying to get() that brings up the same error. ( IndexOutOfBounds ) I also tried not using the ensureCapacity, I was under the impression ArrayList automatically expanded as it was necessary to fit items. ( I know they arent LinkedLists but would operate similiarly) Thanks for any help.
Maulin Vasavada
Ranch Hand
Joined: Nov 04, 2001
Posts: 1865
posted
0
well the issue is indexing starts from 0 not 1
try, //check if LinkedList at position exists if(array.get(pos-1)==null){ //add new LinkedList to array array.add(pos-1,new LinkedList()); }
i take that back. it might not work. i'm writing test program.
Rich Stepanski
Ranch Hand
Joined: Aug 24, 2004
Posts: 59
posted
0
i tried to just ensureCapacity(pos+1) - that didnt work either.. thanks for trying , any other ideas?
Maulin Vasavada
Ranch Hand
Joined: Nov 04, 2001
Posts: 1865
posted
0
Hi Rich,
I found the problem. In the JDK1.4.2_03 source of ArrayList I see,
if (index > size || index < 0) throw new IndexOutOfBoundsException( "Index: "+index+", Size: "+size);
in add(index,object) method.
Now, the problem is when we call ensureCapacity(), it doesn't update the size as that call doesn't "add" any element in the array. Size variable reflects how many elements are there not how many it can hold.
So even when you call ensureCapacity(pos) size doesn't change and add(pos,data) fails as index > size
I guess you might have to override ArrayList's add(index,object) method to fit your needs...thinking more over it..
Regards Maulin
Maulin Vasavada
Ranch Hand
Joined: Nov 04, 2001
Posts: 1865
posted
0
So in essense we can only call add(index,object) method when we really want to "insert" in the array. Here the given index is surrounded by some elements already in the array.
Also, in the API it says "throws IAE if index is out of range of 0,size" so I guess its clear.
Now to solve your problem, I think you are trying some sort of hash table impl yourself. Why not create Integer as key and use Hashtable/HashMap? that will work for you...
Regards, Maulin
Rich Stepanski
Ranch Hand
Joined: Aug 24, 2004
Posts: 59
posted
0
Thanks for the help, I'll try something different.