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

2011/7/23

how to remove all objects in the world

nooby123 nooby123

2011/7/23

#
how can i remove all existing objects in the world?
danpost danpost

2011/7/23

#
First add the import statement
import java.util.List;
to the top of the method class; (Thanks Herman, my bad) Then use
List objects = getObjects(null);
removeObjects(objects);
within the code to remove all objects in the world.
danpost danpost

2011/7/23

#
BTW, if there is a chance that there are no objects to remove, change line 2 to
if (objects != null) { removeObjects(objects); }
or
if (objects.size > 0) { removeObjects(objects); }
Herman Herman

2011/7/24

#
Unless a class and a method are the same, I suggest to put the import statements in a class. Agree?
Herman Herman

2011/7/24

#
Then you also can remove all the objects in the actor class with: List remove = getObjects( Actor.class ); for (Object objects : remove) removeObject( ( Actor ) objects );
Advenging Advenging

2011/7/24

#
.
mik mik

2011/7/24

#
You got all the right bits here somewhere, but just to clarify: The correct code is (assuming you are in the World class):
import java.util.List;  
...

List<Actor> actors = getObjects(null);  
removeObjects(actors);
or alternatively, just:
removeObjects(getObjects(null));
In the second case, you don't need the import. The check if (objects != null) ... is wrong. getObjects will never return null. If there are no objects, it will return an empty list (which is not the same as null). The check if (objects.size > 0) ... which could also be written as if (objects.isEmpty()) ... is not needed, as the removeObjects method works perfectly well with an empty list, so it's not a mistake to pass an empty list to it. The last version mentioned by Herman works, but is unnecessarily long. removeObjects(List) does exactly the same as calling removeObject(Actor) in a loop.
nooby123 nooby123

2011/7/24

#
Thanks
danpost danpost

2011/7/24

#
@mik, thanks michael -- I knew one of the two would work, so I gave both with the 'or'. Though, it makes sense that it would be the one it is. It still would create a List object, even if it is empty. It also makes sense that 'removeObjects(List)' would work on an empty list. Thanks, again.
You need to login to post a reply.