| Author |
Collection size incosistency
|
Alex Teslin
Ranch Hand
Joined: Jan 16, 2006
Posts: 49
|
|
Hi, I am doing some tests on collectons and find some unexpected results. eg, with ArrayList i am adding values to ArrayList timing that and immediately removing those values. Part of the code: for(int i = 0; i < SIZE; i++) { values.add(new Integer(nextValue())); } for(int i = 0; i < values.size(); i++) { values.remove(i); } Now, after removing values when i print the size of the collection, there still exactly half of the values left. Can any one please tell me why is it half empty? I am looping every index until the values.size() to remove them. I just don't undertand?
|
 |
Alex Teslin
Ranch Hand
Joined: Jan 16, 2006
Posts: 49
|
|
|
I think because ArrayList doubles the initial size once the size is full (I think)
|
 |
Reid M. Pinchback
Ranch Hand
Joined: Jan 25, 2002
Posts: 775
|
|
Take a very close look at the loop condition in the second loop. Compare it to what is going on in the body of that second loop. Your eyes are telling your brain something that isn't true. You'll laugh when you figure it out. Everybody probably goes through it once. [ February 16, 2006: Message edited by: Reid M. Pinchback ]
|
Reid - SCJP2 (April 2002)
|
 |
Alex Teslin
Ranch Hand
Joined: Jan 16, 2006
Posts: 49
|
|
|
Is it because the value.size decrements and the i loop increments the same time?
|
 |
Reid M. Pinchback
Ranch Hand
Joined: Jan 25, 2002
Posts: 775
|
|
|
Yup. You are calling a method on an object that you are mutating. Every time you ask it for the size, it gives it to you. Just not the same size.
|
 |
Alex Teslin
Ranch Hand
Joined: Jan 16, 2006
Posts: 49
|
|
|
Thank you for your tip
|
 |
Stefan Wagner
Ranch Hand
Joined: Jun 02, 2003
Posts: 1923
|
|
I would say, asking for the size isn't wrong, but incrementing, since remove (i) will make element i diappear, and element (i+1) is becoming i. will show what's happening, and will solve the problem.
|
http://home.arcor.de/hirnstrom/bewerbung
|
 |
Reid M. Pinchback
Ranch Hand
Joined: Jan 25, 2002
Posts: 775
|
|
One thing to note (since this is the performance forum) is that for array-backed lists all these variations are likely sub-optimal. Lots of array copying going on. Wouldn't be an issue for elements deleted from the end, and the original problem Alex had wouldn't have even shown up in that case. [ February 16, 2006: Message edited by: Reid M. Pinchback ]
|
 |
Vlado Zajac
Ranch Hand
Joined: Aug 03, 2004
Posts: 244
|
|
You can also remove all values in one method call
|
 |
 |
|
|
subject: Collection size incosistency
|
|
|