繁体   English   中英

如何删除ArrayList中的对象

[英]How to remove objects in ArrayList

我如何实现删除ArrayList中的对象。 我尝试了以下代码,但粒子没有消失。 我输出了removeQue ArrayList的大小,并输出了1。checkCollide方法可以很好地检测冲突。

这在一个名为“粒子”的类中

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

更多规格:

这是整个班级:

导入java.util.ArrayList; 导入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();
     }
   }

我不确定您是否正确描述了这种情况。

removeQue.clear()

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM