如何删除ArrayList中的对象

时间:2016-02-21 19:21:29

标签: java arraylist

如何在ArrayList中实现删除对象。我尝试了以下代码,但粒子不会死。我输出了removeQue ArrayList的大小并输出1. checkCollide方法可以很好地检测碰撞。

这是在名为Particles的类

  public void Update(){
    for(Enemies e: Enemies.enemies){
      if(this.checkCollide(e.x,e.y,e.mass)){
        removeQue.add(this);
      }
    }
    removeQue.clear(); // Remove objects
  }

更多规格:

以下是全班:

import java.util.ArrayList; import java.awt。*;

public class Particle{

  public static ArrayList<Particle> particles = new ArrayList<Particle>();
  public static ArrayList<Particle> removeQue = new ArrayList<Particle>();

  public static int particleCount;

  private int x,y,r,g,b,mass;

  private boolean playerParticle = false;

  private Color color = new Color((int)Math.floor(Math.random() * 256),(int)Math.floor(Math.random() * 256),(int)Math.floor(Math.random() * 256));

  public Particle(int x,int y, int mass, boolean p){
    particleCount++;
    this.x = x;
    this.y = y;
    this.mass = mass;
    playerParticle = p;
  }

  public void Update(){
    for(Enemies e: Enemies.enemies){
      if(this.checkCollide(e.x,e.y,e.mass) && !playerParticle){
        if(e.mass <= 200){
          e.addMass(this.mass);
        }
        if(e.mass >= 200){
          e.isTarget = false;
          e.goalReached = true;
          e.targetType = "c";
        }
        if(e.targetType.equals("p")){
          e.goalReached = true;
          e.isTarget = false;
        }
        this.x = (int) Math.floor(Math.random() * 10001);
        this.y = (int) Math.floor(Math.random() * 10001);
      }else if(this.checkCollide(e.x,e.y,e.mass) && playerParticle){
        e.addMass(this.mass);
        removeQue.add(this);
      }
    }
    removeQue.clear();
  }

  private boolean checkCollide(double x,double y,double mass){
    return x < this.x + 10 && x + mass > this.x && y < this.y + 10 && y + mass > this.y;
  }

  public void Draw(Graphics bbg){
    bbg.setColor(color);
    bbg.fillRect(x,y,10,10);
    bbg.drawRect(x,y,10,10);
  }


}

这是我的主要更新方法

public void update(){
     for(Particle p: Particle.particles){
       p.Update();
     }

     for(Enemies e: Enemies.enemies){
       e.Update();
     }
   }

1 个答案:

答案 0 :(得分:1)

我不确定你是否正确描述了这种情况。之后

removeQue.clear()
调用

,ArrayList的大小应为0,因为它是方法的最后一行。

相关问题