0

I'm want to create an ArrayList that contains an Array and call the function of the objects inside that array.

I'm trying to call the function display() inside of the Array but I'm getting a NPE even though the array contains an object.

this is my code:

class Ball
{
  int x;
  int y;
  int size;
  color c;

  Ball()
  {
    x = int (random(width));
    y = int (random(height));
    size = int (random(100));
    c = color(random(255));
  }

  void display()
  {
    fill(c);
    ellipse(x,y,size,size);
  }
}

ArrayList<Ball[]> balls;


void setup()
{
  size(500,500);

  balls = new ArrayList<Ball[]>();

  for( int i = 0; i < 1; i++)
  {
    balls.add(new Ball[2]);
    println(balls);
  }
}

void draw()
{
  background(255);

  for( int i = 0; i < 1; i++)
  {
    Ball[] b = balls.get(i);
    b[i].display();
  }
}

does anybody know how to do this?

4
  • balls.get(0)[0].display() would work Commented Apr 28, 2016 at 21:00
  • 2
    Your problem is that you're not creating any Balls - only an empty array. Commented Apr 28, 2016 at 21:01
  • 2
    The array is empty. You didn't create any balls. Commented Apr 28, 2016 at 21:02
  • The array does not contain a non-null object reference. Even though you clearly stated that it did in English, you didn't enforce that in Java. Since the compiler only reacts to the Java source, you will need to reflect your assertion in your code. Commented Apr 28, 2016 at 21:59

1 Answer 1

1

You have a list of empty Ball arrays. Add balls after creating the (empty) array:

void setup()
{
  size(500,500);

  balls = new ArrayList<Ball[]>();

  for( int i = 0; i < 1; i++)
  {
    Ball[] ballsArray = new Ball[2];
    ballsArray[0] = new Ball();
    ballsArray[1] = new Ball();
    balls.add(ballsArray);
    println(balls);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.