从另一个 class 修改 ArrayList 对象值

Modifying ArrayList object values from another class

我有两个 classes:class 包含 ArrayList 类群的生物和 class 食物。 Boids 有几个参数:

 Creature(float posX, float posY, int t, int bth, int ah) {
    location = new PVector(posX, posY);
    vel = new PVector(random(-5,5), random(-5, 5));
    acc = new PVector();
    type = t;
    if (t == 1) { btype = bth; }
    else { health = bth; }
    if (t == 1) { age = ah; }
    else { hunger = ah; }
    wdelta = 0.0;
    action = 0;
    if (btype == 1) { mass = 5.0; }
    else { mass = 7.0; }
  }

食物class有这个方法:

  void foodtime(ArrayList boids) {
    for (int i = 0; i < boids.size(); i++) {
      Creature boid = (Creature) boids.get(i);
      float distance = PVector.dist(location, boid.location);
      if (distance < 0.5) {
        bnumadj = i;
        count++;
        if (count == quantity) {
          planet.food.remove(this);
          count = 0;
          bnumadj = -1;
        }
      }
    }
  }

我想要实现的是,如果一个 boid "eats" 食物,它们的 boid 类型 (btype) 从 2 变为 1。

我正在尝试使用 bnumadj 变量将其反馈给此方法中的 boid:

  void boid(ArrayList boids) {
    for (int i = 0; i < boids.size(); i++) {
      if (i == bnumadj) {
        this.btype = 1;
        bnumadj = -1;
      }
    }
  }

我哪里错了?

这似乎是一种非常复杂的方法,所以我对您遇到问题并不感到惊讶。您将值与索引进行比较,这对我来说意义不大。

相反,请尝试使用简单的嵌套循环来执行您想要的操作。您可以使用 Iterator 以便在迭代时更轻松地删除项目。

ArrayList<Creature> boids = new ArrayList<Creature>();
ArrayList<Food> food = new ArrayList<Food>();
//populate ArrayLists

void draw(){

   for(Creature boid : boids){
      Iterator<Food> foodIter = food.iterator();

      while(foodIter.hasNext()){
         Food f = foodIter.next();
         float distance = PVector.dist(boid.location, food.location);
         if (distance < 0.5) {
            boid.btype = 1;
            foodIter.remove(); //removes the food
        }
      }

   }

   //draw the scene
}

我想您可以使用 Creature 类型中的 Iterator 移动第二次迭代,但基本思想是:通过使用 Iterator 删除Food 而不是尝试匹配索引。