Array Lists

Arraylists are a technique for building collections, like in the last tutorial I learnt how to build a class and duplicate the class instances so there were three balls, arraylists enable me to do this without having to write out the class instances loads of times.

You start by defining an arraylist at the beginning of the code, here I’ve named it ‘ballCollection.’ Then you build a new class instance in the initialize section of code and then add that instance to the arraylist.

And then you have to run the first element of the array list in the call function section. In this part you can set the x and y coordinates of where the collection will start to appear on the canvas.

Then using a for loop you can say how many instances are in the collection. This is done in the void setup section then repeated in the void draw part where it calls the class instance to the element i which is defined within the for loop.

I played around with adding random colours as well to make it look a bit cooler.

//Declares the class then class instance 
ArrayList ballCollection;
void setup(){
//Initializes the class. New is saying create a new instance of the class 'Ball'
ballCollection = new ArrayList();
for(int i = 0; i<100; i++){
Ball myBall = new Ball(random(0, width),random(0,400));
void draw(){
 //Calls the function of the class. The '.' opens up the class. 
 for(int i = 0; i<100; i++){
 Ball myBall = (Ball) ballCollection.get(i);;
class Ball {
//global variables. location, speed...
 float x=0;
 float y=0;
 float speedX = 4;
 float speedY = 0.5;
//constructor. how to build the class, calling variables, happens just once.
 Ball(float _x, float _y) {
x = _x;
 y = _y;
 void run() {
void gravity() {
 speedY += 0.2;
 void bounce() {
if (x > width) {
 speedX = speedX * -1;
 if (x < 0) {
 speedX = speedX * -1;
 if (y > height) {
 speedY = speedY * -1;
 if (y < 0) {
 speedY = speedY * -1;
 void move() {

x += speedX;
y += speedY;
void display() {
ellipse(x, y, 30, 30);



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s