【发布时间】:2021-03-13 01:21:55
【问题描述】:
我有一个带有对象 Player 的 ArrayList。当我尝试从列表中删除此对象时,我在控制台中没有收到任何错误,但该对象并未被删除。这是因为如果我 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中的对象(Player),在程序第一次运行时调用:
public void renderCreatures() {
handler.getCreatureManager().addCreature(new Player(handler, 1280, 720));
}
arraylist 中的对象 (Player) 正在被删除,并且 arraylist(它被一个名为 getPlayer() 的 getter 调用,它返回 arraylist)随后被打印到控制台,如下所示:
handler.getCreatureManager().removeCreature(handler.getCreatureManager().getPlayer());
System.out.println(handler.getCreatureManager().getCreatures());
控制台中的输出(来自arraylist的Sysout)证明刚刚移除的对象还在arraylist中:
[dev.l0raxeo.entities.creatures.Player@3661db4d]
【问题讨论】:
-
我会看看如何在 Player 类上实现 equals() 方法,因为它在删除期间被使用。如果它总是返回 false,那么该对象将不会在列表中找到并且不会被删除。
-
添加的
Player对象和您尝试删除的Player对象不同。尝试以这种方式添加handler.getCreatureManager().addCreature(handler.getCreatureManager().getPlayer());。 -
我有点困惑。我是一名自学成才的程序员,我只有 13 岁,所以我不太确定你们建议我做什么......
-
Player需要实现toequals(Object o)方法,以及hashCode()方法。
-
谢谢大家我解决了:)
标签: java arraylist getter-setter