a port of the Processing Visualization Language


// This is a code fragment that shows how to use an ArrayList.

// It won't compile because it's missing the Ball class.

ArrayList balls;

void setup() {

  size(200, 200);

  balls = new ArrayList();  // Create an empty ArrayList

  balls.add(new Ball(width/2, 0, 48));  // Start by adding one element


void draw() {


  // 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--) { 

    // An ArrayList doesn't know what it is storing so we have 

    // to cast the object coming out

    Ball ball = (Ball) balls.get(i);



    if (ball.finished()) {

      // Items can be deleted with remove()





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.

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.

initialCapacity int: defines the initial capacity of the list, it's empty by default
Usage Web & Application

This reference is licensed under the CC BY-NC-SA 2.0 license:

Creative Commons License
Fork me on GitHub