I have a list full of many classes and in each class I would like to know a way that allows me to remove itself like this:
public class World{
List<Entity> Entities;
}
public class Entity{
public void removeselffromlist()
{
//code i dont know
}
}
Edit:There will not be multiple开发者_StackOverflow worlds
You would have to make the list available to the other class. One possible solution would be:
public class World {
List<Entity> entities;
public void removeItem(Entity entity) {
entities.remove(entity);
}
}
public class Entity{
public void removeSelfFromList() {
world.removeItem(this);
}
}
Note that you would need to have a "world" object somewhere.
In order to be able to remove itself from the list, the Entity
class requires a reference to it. One means of achieving this is to control addition to / removal from the list via public methods on the World
class; e.g.
public class World {
private final List<Entity> entities;
public void addEntity(Entity entity) {
if (entity.getWorld() != null) {
throw new IllegalArgumentException("Entity already associated with a world: " + entity);
}
entities.add(entity);
entity.setWorld(this);
}
public void removeEntity(Entity entity) {
if (entity.getWorld() != this) {
throw new IllegalArgumentException("Entity is not associated with this world: " + entity);
}
entities.remove(entity);
entity.setWorld(null);
}
}
public class Entity {
private World world;
public World getWorld() { return world; }
public void setWorld(World world) { this.world = world; }
public void remove() {
world.removeEntity(this);
}
}
While I question this whole approach (without knowing a specific reason why you'd need to do this), the answer is that the Entity
class would need access to at least aWorld
instance, if not the Entities
list directly. Note that you should be using camelCase; variables should never start with an uppercase letter.
public class World{
private List<Entity> myEntities;
public void addEntity(Entity e)
{
myEntities.add(e);
e.setWorld(this);
}
public void removeEntity(Entity e)
{
myEntities.remove(e);
}
}
public class Entity{
private World myWorld;
public setWorld(World w)
{
this.myWorld = w;
}
public void removeselffromlist()
{
//code i dont know
myWorld.removeEntity(this);
}
}
If I were doing something like this, I'd move all creation, ownership and management of Entity
objects inside the World
class.
精彩评论