This site requires JavaScript, please enable it in your browser!
Greenfoot back
MarcSavoie
MarcSavoie wrote ...

2015/6/28

how do i remove a specific object from a list?

MarcSavoie MarcSavoie

2015/6/28

#
I have a list with 13 objects from one class of which a few have the variable "isUsed" set to true and the others to false. How can i remove the objects which have it set to true from the list?
Super_Hippo Super_Hippo

2015/6/28

#
1
2
3
4
5
6
for (Object obj: nameOfTheList) //for each element in the list
{
    ClassName cn = (Classname) obj; //cast the object, so you can use the 'isUsed' variable
    if (cn.isUsed) getWorld().removeObject(cn); //without 'getWorld' if it is used in a world subclass
    //if 'isUsed' isn't public, call the getter method instead
}
fejfo fejfo

2015/7/1

#
Super_Hippo: I think he meant to remove it form the list and not from the world. so :
1
2
3
4
5
6
7
List<> copy = nameOfTheList
for (Object obj: copy) //for each element in the list
{
    ClassName cn = (Classname) obj; //cast the object, so you can use the 'isUsed' variable
    if (cn.isUsed) nameOfTheList.remove(cn);
    //if 'isUsed' isn't public, call the getter method instead
}
davmac davmac

2015/7/1

#
fejfo, it looks like you are trying to make a copy of the list, before you iterate through the copy and remove the elements from the original list that you don't want. This is ok in principle, but:
1
List<> copy = nameOfTheList
This does NOT make a copy of the list. It just sets the 'copy' variable to refer to the same original list. Also it would give an error because the diamond operator cannot be used in a variable declaration for the variable type. You should instead do:
1
List copy = new ArrayList(nameOfTheList);
(and you need to import ArrayList, i.e. "import java.util.ArrayList"). An alternative which avoids copying the list first is to use an iterator:
1
2
3
4
for(Iterator i = nameOfTheList.iterator(); i.hasNext(); ) {
    ClassName cn = (Classname) i.next();
    if (cn.isUsed) i.remove();
}
fejfo fejfo

2015/7/1

#
I tried to avoid the current modification exception (which I have got a lot of trouble with)
davmac davmac

2015/7/1

#
fejfo wrote...
I tried to avoid the current modification exception (which I have got a lot of trouble with)
Yes, I understand that was what you were trying to do, but the code you provided does not avoid it because it doesn't actually copy the list. You need to either actually copy the list (as in the example I gave) or use an iterator to process the list (as in the second example I gave).
MarcSavoie MarcSavoie

2015/7/1

#
thanks a lot guys, very helpful responses. :)
Super_Hippo Super_Hippo

2015/7/1

#
fejfo wrote...
Super_Hippo: I think he meant to remove it form the list and not from the world.
Yeah, you are right. It looks like I only read the post, but not the title.
You need to login to post a reply.