Reputation: 25
No mather what i try i cannot seem to remove all the objects in my list. I always end up removing half of the items, while the other half remains for some reason.
Any input greatly appreciated.
private List<Connection> listCon = new ArrayList<Connection>();
public void addConnection()
{
listCon.add(new Connection(isConnected));
}
public void inActivate()
{
for(int i=0; i < listCon.size(); i++)
{
removeConnection(listCon.get(i));
}
}
public void removeConnection(Connection c)
{
listCon.remove(c);
}
Upvotes: 2
Views: 257
Reputation: 11
why not just use, listCon.clear()
?
Failing that, reverse your loop:
for(int i = listCon.size -1; i >=0; i--) {
listCon.remove(i);
}
or as Will Kru suggests, always remove the 0th element
Finally, use an iterator and iterator.remove:
for(Iterator<Connection> i = listCon.iterator(); i.hasNext();) {
Connection c = i.next();
i.remove();
}
Upvotes: 1
Reputation: 77722
The classical problem of deleting objects from a list while you're iterating through it.
for(int i=0; i < listCon.size(); i++)
{
removeConnection(listCon.get(i));
}
You
Many solutions to this. One common one is to delete element 0 until the size is 0.
EDIT: If your goal is really just to clear the array with no other operations, then listCon.clear()
is by far the better approach. I'm assuming though that removeConnection
does more than just removing the element from the list, you just didn't show that to keep your example simple.
Upvotes: 7
Reputation: 533492
You are removing every second item because you are altering the list while you loop. i.e. you remove the 0th element, in which case the 1th element takes it place and you move onto the new 1th element etc. If you used a debugger you would see this happening.
The simplest thing to do is to remove the elements in reverse order as this doesn't result in elements being shifted around.
for(int i=listCon.size()-1; i>=0; i--)
removeConnection(listCon.get(i));
Upvotes: 3
Reputation: 5212
You are changing the array structure while looping over it, which is a really bad idea as you experienced. Because the array elements get shifted once you remove an element, you will skip elements.
The best way to do this is using a while loop:
while(listCon.size() > 0){
listCont.remove(0);
}
@ebomike beat me to it
Upvotes: 2
Reputation: 122381
You are changing what is referenced by 'i' after removing an object from the list in this method:
public void inActivate()
{
for(int i=0; i < listCon.size(); i++)
{
removeConnection(listCon.get(i));
}
}
Instead, use an iterator:
Iterator it = listCon.iterator();
while(it.hasNext())
{
it.remove();
}
or in this case, just clear the list:
listCon.clear();
Upvotes: 5
Reputation: 759
What about using the lists .clear() method?
And if you really need to remove step by step while iterating you should use the lists iterator and its remove() method.
Upvotes: 2