ArrayList of objects

ArrayList of objects by Daniel Shiffman.

This example demonstrates how to use a Java ArrayList to store a variable number of objects. Items can be added and removed from the ArrayList. * Click the mouse to add bouncing balls.

ArrayList<Ball> balls;
int ballWidth = 48;

void setup() {
  size(640, 360);

  // Create an empty ArrayList (will store Ball objects)
  balls = new ArrayList<Ball>();
  // Start by adding one element
  balls.add(new Ball(width/2, 0, ballWidth));

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 = 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));

// Simple bouncing ball class

class Ball {
  float x;
  float y;
  float speed;
  float gravity;
  float w;
  float life = 255;
  Ball(float tempX, float tempY, float tempW) {
    x = tempX;
    y = tempY;
    w = tempW;
    speed = 0;
    gravity = 0.1;
    void move() {
    // Add gravity to speed
    speed = speed + gravity;
    // Add speed to y location
    y = y + speed;
    // If square reaches the bottom
    // Reverse speed
    if (y > height) {
      // Dampening
      speed = speed * -0.8;
      y = height;
  boolean finished() {
    // Balls fade out
    if (life < 0) {
      return true;
    } else {
      return false;
  void display() {
    // Display the circle

Functions Used


Sets the color used to fill shapes

Learn More

Sets the color used to draw lines and borders around shapes

Learn More

Defines the dimension of the display window width and height in units of pixels

Learn More

Draws an ellipse (oval) to the screen

Learn More

Reads the color of any pixel or grabs a section of an image

Learn More

The setup() function is run once, when the program starts

Learn More

Called directly after setup(), the draw() function continuously executes the lines of code contained inside its block until the program is stopped or noLoop() is called

Learn More

The mousePressed() function is called once after every time a mouse button is pressed

Learn More

Disables drawing the stroke (outline)

Learn More

The background() function sets the color used for the background of the Processing window

Learn More