使用ArrayList

书名:代码本色:用编程模拟自然系统
作者:Daniel Shiffman
译者:周晗彬
ISBN:978-7-115-36947-5
目录

4.3 使用ArrayList

  • 我们可以使用数组管理这些粒子对象。如果粒子系统的粒子数量是恒定的,数组是非
    常有效的工具。
    此外,Processing还提供了一些函数用于改变数组长度,
    比如expand()、contract()、subset()、splice()等。
  • 在本章,我们要使用Java的ArrayList类,
    这是一种更高级的对象列表管理方法。
    你可以在java.util包中找到该类的相关文档
(http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html)

1、管理

  在系统中创建和添加粒子对象,移除消亡的粒子对象。

2、迭代器

  可以满足你各种各样的遍历需求。

  • ArrayList的iterator()函数会返回一个迭代器对象。
  • 得到迭代器对象之后,它的hasNext()函数会告诉我们是否有下一个粒子对象,
  • 而调用next()函数得到这个粒子对象。
  • 在遍历过程中,如果你用迭代器调用了remove()函数,当前的粒子对象就会被删除
    (接着向前遍历ArrayList,下一个对象并不会被跳过)。

3、示例

示例代码4-2 用迭代器遍历ArrayList

ArrayList<Particle> particles;

void setup() {
  size(640, 360);
  particles = new ArrayList<Particle>();
}

void draw() {
  background(255);

  particles.add(new Particle(new PVector(width/2, 50)));

  // Looping through backwards to delete
  for (int i = particles.size()-1; i >= 0; i--) {
    Particle p = particles.get(i);
    p.run();
    if (p.isDead()) {
      particles.remove(i);
    }
  }
}

Particle.pde

class Particle {
  PVector position;
  PVector velocity;
  PVector acceleration;
  float lifespan;

  Particle(PVector l) {
    acceleration = new PVector(0, 0.05);
    velocity = new PVector(random(-1, 1), random(-2, 0));
    position = l.copy();
    lifespan = 255.0;
  }

  void run() {
    update();
    display();
  }

  // Method to update position
  void update() {
    velocity.add(acceleration);
    position.add(velocity);
    lifespan -= 2.0;
  }

  // Method to display
  void display() {
    stroke(0, lifespan);
    strokeWeight(2);
    fill(127, lifespan);
    ellipse(position.x, position.y, 12, 12);
  }

  // Is the particle still useful?
  boolean isDead() {
    if (lifespan < 0.0) {
      return true;
    } 
    else {
      return false;
    }
  }
}

4、运行结果

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容