【发布时间】:2015-05-13 10:31:01
【问题描述】:
关于如何从 ArrayList 中删除特定元素而不是 ArrayList 的 Iterator 存在一些问题。使用下面的代码,它删除了 ArrayList 中的所有元素,但我想删除特定元素,即与播放器发生碰撞的元素。谁能告诉我如何更改此代码以使其这样做?提前致谢。
public void update() {
for(Iterator<Object> iter = list.iterator(); iter.hasNext();) {
Object o = iter.next();
o.update();
if(Enemy.collide == true) {
iter.remove();
}
}
}
这是对象类(敌人和玩家类扩展了它):
package game;
public abstract class Object {
protected float x;
protected float y;
protected float sX, sY;
abstract void update();
public void render() {
Draw.Rect(x, y, sX, sY);
}
public float getX() {
return x;
}
public float getY() {
return y;
}
public float getSX() {
return sX;
}
public float getSY() {
return sY;
}
public float getCenterY() {
return y + sY/2;
}
public void removeObject(Object o) {
Game.list2.remove(o);
Game.list = Game.list2;
Enemy.collide = false;
}
}
敌人等级:
package game;
import java.util.Iterator;
public class Enemy extends Object {
private int i = 0;
private int health = 100;
private int point = 0;
static boolean collide = false;
Enemy(float x, float y) {
this.x = x;
this.y = y;
this.sX = Player.size;
this.sY = Player.size;
}
void update() {
if(Physics.checkCollision(this, Game.player)) {
collide = true;
}
if(Math.abs(Game.player.x - this.x) <= 30 && Math.abs(Game.player.x - this.x) >= 1 && Physics.checkCollision(this, Game.player) != true) {
switch(i) {
case 1:
break;
case 0:
if(Game.player.x >= this.x) this.x++;
if(Game.player.x <= this.x) this.x--;
if(Game.player.y >= this.y) this.y++;
if(Game.player.y <= this.y) this.y--;
break;
}
}
}
}
播放器类:
package game;
public class Player extends Object {
public final static float size = 30;
public Player(float x, float y) {
this.x = x;
this.y = y;
this.sX = size;
this.sY = size;
}
public void update() {
}
public void moveY(double magY) {
y += magY;
}
public void moveX(double magX) {
x += magX;
}
}
【问题讨论】:
-
不,我们不能,因为我们不知道
Enemy.collide是什么(除了它是一个在您的代码上下文之外设置的 single 布尔值给定)。您需要使Enemy.collide与列表中的特定条目相关,也许是您调用的将项目传递到或类似的方法。 -
你确定
Enemy.collide对其他人来说是假的。它似乎是一个静态字段。 -
没有
Enemy类代码,你的问题毫无意义。 -
您的
Enemy.collide属性似乎是静态的并且独立于对象o。 -
等等...
o.update()? javaObject中没有update()函数!请切勿致电个人课程Object。这令人困惑,并可能导致导入问题。