Cake holders

Now you’ve learned how to bake some delicious Cake objects (hop over here if you’ve forgotten!), we need something to put them in.

Step forward arrays.

Arrays are a special sort of list – they have slots in them, like an old-fashioned milk bottle holder, that you can place things into. The restriction is that you have to tell Processing when you create your list both how big you want it to be, and what sorts of thing you want to put into it. Afterwards, your array can only hold a maximum of that number of those particular objects.

For example, you could declare an array to hold milk bottles of size 6 like this:

milkbottles[] carrier = new milkbottles[6] # as long as milkbottles exists as an object!

Or one just for 10 ints like this:

int[] intholder = new int[10]

Confusingly (well, for a special reason that I won’t go into here but you can find out more about over there), the first ‘slot’ in an array is always the zeroth slot. This means the last slot is always (number of things the array can hold – 1).

What?

OK – say we made an array specailly for cakes with 3 slots like this:

 Cake[] holder = new Cake[3];

… and added 3 pre-existing cake objects into each slot in turn like this ….

holder[0] = cake1;
holder[1] = cake2;
holder[2] = cake3;

Our cakes holder now looks like this:

[cake1, cake2, cake3]

If we wanted to access the first item, we’d do this:

Cake mycake = holder[0]

And get the “cake1” object back.

Processing is a bit fussy about arrays – if you say to it “give me the thing in the fifth slot” and there is no fifth slot, then it will complain :). Also remember that if you haven’t added something to the slot, you’ll get a null back!

You can use the “length” property to find out how many things are in the array. Then you can access the last item using (length – 1).

So, for our cake holder:

numberOfCakes = holder.length # returns 3
lastCake = holder[numberOfCakes - 1] # returns cake3
Bookmark the permalink.

Comments are closed.