java - 修改另一个类中的 ArrayList 对象值

标签 java arraylist processing boids

我有两个类:包含 ArrayList boids 的 Creature 类和 Food 类。 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; }
  }

Food类有这个方法:

  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“吃”了食物,它们的 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;
      }
    }
  }

我哪里出错了?

最佳答案

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

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

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 而不是尝试匹配索引。

关于java - 修改另一个类中的 ArrayList 对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35068329/

相关文章:

java - OKHTTP,带有进度条的调度程序

java - Java 中的 ArrayList 排序

java - java中Hashmap和ArrayList添加值的方式不同

java - 如何过滤FFT数据(用于音频可视化)?

java - 如何导出具有外部 Jar 依赖项的 Eclipse 项目?

java - 如何在 Java 上 GZIP 文件并通过 OutputStream 发送

java - getResourceAsStream() 总是返回 null

java - 有没有办法将 java 方法声明为 kotlin 的中缀

java - 比较字符串数组列表和字符串数组

java - 使用处理连接arduino串口的问题