NullPointerException with ArrayList of Objects

So I am trying to get a list of objects, that when something is pressed, it will add new objects to the list to be checked. I keep getting NullPointerException and I can’t figure it out. I have tried adding a new item when I press a key and simplified the code down to just the error, but it isn’t working for me. I don’t understand how I can get a NullPointerException when trying to create a new item. Thank you in advance.

class Dots {
  PVector position = new PVector(random(width), random(height));
  PVector velocity = new PVector(1, 1);
  PVector acceleration = new PVector(1, 1);
  
  void updatePos() {
   velocity.add(acceleration);
   position.add(velocity);
   circle(position.x, position.y, 10);
  }
}

ArrayList<Dots> dotsList;

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

void draw() {
  background(0);
  //for (int i = 0; i < 1; i++) {
  //  circle(dotsList.get(i).position.x, dotsList.get(i).position.y, 10);
  //}
  if (keyCode == CONTROL) {
    dotsList.add(new Dots());  
  }
}
1 Like

Welcome to the forum!

This ArrayList dotsList; should
be ArrayList dotsList=new ArrayList ();
or
ArrayList<Dots> dotsList=new ArrayList ();

Telling the arraylist its type.

Maybe in setup you need to add one dot

Your for loop is not okay

Convention: your class could be named singular, since it’s only one dot. Starting with a capital letter is correct

Regards, Chrisir

2 Likes