我有一个对象播放器的数组列表。当我试图从列表中删除此对象时,控制台中没有任何错误,但该对象没有被删除。这是因为如果我输入system.out.println(arraylist);在我移除对象之后,它仍然打印出刚刚移除的对象。
我在这里管理并创建arraylist:
public class CreatureManager {
protected Handler handler;
private ArrayList<Creature> creatures;
private final Player player;
public CreatureManager(Handler handler) {
this.handler = handler;
player = new Player(handler, 1280, 720);
creatures = new ArrayList<>();
}
public void addCreature(Creature e) {
creatures.add(e);
}
public void removeCreature(Creature e) {
creatures.remove(e);
}
public void tick() {
for (Creature e : creatures) {
e.tick();
}
}
public void render(Graphics g) {
for (Creature e : creatures) {
e.render(g);
}
}
public Player getPlayer() {
return player;
}
public ArrayList<Creature> getCreatures() {
return creatures;
}
}
arraylist中的泛型“creataure”指的是以下类:
public abstract class Creature {
protected Handler handler;
protected int x, y;
protected int width, height;
protected Rectangle bounds;
public Creature(Handler handler, int x, int y, int width, int height) {
this.handler = handler;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
bounds = new Rectangle(0, 0, width, height);
}
public abstract void tick();
public abstract void render(Graphics g);
}
arraylist中的对象(播放器)添加到此处,并在程序首次运行时调用:
public void renderCreatures() {
handler.getCreatureManager().addCreature(new Player(handler, 1280, 720));
}
arraylist中的对象(player)将被删除,而arraylist(使用名为getplayer()的getter调用,getter返回arraylist)将被打印到控制台,如下所示:
handler.getCreatureManager().removeCreature(handler.getCreatureManager().getPlayer());
System.out.println(handler.getCreatureManager().getCreatures());
控制台中的输出(从sysout到arraylist)证明刚刚删除的对象仍然在arraylist中:
[dev.l0raxeo.entities.creatures.Player@3661db4d]
1条答案
按热度按时间lskq00tm1#
当你打电话的时候
renderCreatures
,您正在添加new Player
但不将引用保存到任何地方(例如player
所以当你打电话的时候getPlayer()
,返回一个不同的Player
对象(如果你打印了getPlayer()
,您会看到这是一个不同的示例。)相反,只需继续添加
player
在构造函数中创建它的列表。