So far we've used arrays when we've had to store multiple values – even an array of objects is perfectly feasible. The issue with arrays is that they're static by nature: changing their size is cumbersome and slow, and may involve useless copying of data back and forth. Inserting values into an array is likewise tricky. There are common situations where we would like to have more flexibility, for example in a game where enemies keep appearing and
dyidisappearing. For this purpose we have lists. Processing has the following kinds available for you:
- And ArrayList which lets you store objects – we'll discuss this in From Data to Pixels
The most common operations you'll need are get() – get an item from the list, append() – add one more at the end, size() – the number of items, useful for looping, and remove() – take out one item from the list. See here for a complete list of available functionality and an example.
Why wouldn't we use lists always then? Traditionally they've been slower than plain arrays, in addition to which they may consume more memory. Furthermore, it's a bit trickier to access the individual elements of a list as opposed to an array.
Using Event Handlers (Callbacks) for Input
Like with the mouse, the simplest way to read the keyboard is to check the global variable keyPressed. If it’s true, key will contain the pressed key. It can be either a character in single quotes or a special value such as ENTER or BACKSPACE.
However, when you get serious about it, both the mouse and keyboard are better supported using event handlers, such as mouseClicked. A simple keyboard example: keyboard.pde. An advanced example of the use of event handlers: eventhandlers.pde
By using event handlers you can be sure that you'll never miss mouse clicks or button presses, unlike with the simpler method. Another plus is that you have more advanced control over the mouse movement, for instance mouseDragged, which would be hard to implement otherwise.
This time let's combine lists and event handlers. Let the user place green dots around the window by clicking the mouse. Store the mouse coordinates in a list so that you can redraw all the dots each frame – clear the window at the beginning of draw(). mousePressed() is a good event handler for this purpose.
Example solution: dotlist.pde