This reference is for Processing 2.0+. If you have a previous version, use the reference included with your software. If you see any errors or have suggestions, please let us know. If you prefer a more technical reference, visit the Processing Javadoc.

Name

ArrayList

Examples
// This is a code fragment that shows how to use an ArrayList.
// It won't compile because it's missing the Ball class.

// Declaring the ArrayList, note the use of the syntax "<Ball>" to indicate
// our intention to fill this ArrayList with Ball objects
ArrayList<Ball> balls;

void setup() {
  size(200, 200);
  balls = new ArrayList<Ball>();  // Create an empty ArrayList
  balls.add(new Ball(width/2, 0, 48));  // Start by adding one element
}

void draw() {
  background(255);

  // With an array, we say balls.length. With an ArrayList,
  // we say balls.size(). The length of an ArrayList is dynamic.
  // Notice how we are looping through the ArrayList backwards.
  // This is because we are deleting elements from the list.
  for (int i = balls.size()-1; i >= 0; i--) {
    Ball ball = balls.get(i);
    ball.move();
    ball.display();
    if (ball.finished()) {
      // Items can be deleted with remove().
      balls.remove(i);
    }
  }
}

void mousePressed() {
  // A new ball object is added to the ArrayList, by default to the end.
  balls.add(new Ball(mouseX, mouseY, ballWidth));
}
Description An ArrayList stores a variable number of objects. This is similar to making an array of objects, but with an ArrayList, items can be easily added and removed from the ArrayList and it is resized dynamically. This can be very convenient, but it's slower than making an array of objects when using many elements. Note that for resizable lists of integers, floats, and Strings, you can use the Processing classes IntList, FloatList, and StringList.

An ArrayList is a resizable-array implementation of the Java List interface. It has many methods used to control and search its contents. For example, the length of the ArrayList is returned by its size() method, which is an integer value for the total number of elements in the list. An element is added to an ArrayList with the add() method and is deleted with the remove() method. The get() method returns the element at the specified position in the list. (See the above example for context.)

For a list of the numerous ArrayList features, please read the Java reference description.
Constructor
ArrayList<Type>()
ArrayList<Type>(initialCapacity)
Parameters
Type Class Name: the data type for the objects to be placed in the ArrayList.
initialCapacity int: defines the initial capacity of the list; it's empty by default
RelatedIntList
FloatList
StringList
Updated on May 19, 2014 05:30:05pm PDT

Creative Commons License