Sometimes you’ll want to hold your objects back and sometimes you’ll want to unleash them.
It all depends on what you are making.
To access serious programming power, we use ArrayLists.
1. Overview of ArrayLists
An ArrayList is similar to making an array of objects. But, ArrayLists give you more functionality! Items in your list can be easily added and removed during the course of a program. This is because an ArrayList is resized dynamically – it is a flexible collection. ArrayLists can also hold more than one type of data type in the same set (ints, floats, objects, etc) while regular arrays can only hold one data type at a time.
There will be times when you only need a simple array and other times when an ArrayList is needed to serve more complex programs.
We write things a little differently here.
Basically, the concepts behind arrays and ArrayLists are similar but the syntax is different.
Elements of an ArrayList are added and accessed like functions(),
(rather than the brackets used with arrays).
Common functions() used to manipulate ArrayLists:
size() = Used when we need to know the size of an ArrayList.
add() = Used when we need to add objects to the ArrayList.
remove() = Used when we need to remove objects from the ArrayList.
get() = Used when we need to grab specific objects out of an ArrayList.
Because the ArrayList tool comes from Java, there is a complete reference on even more functions() from Java’s website here.
2. The Syntax of Array Lists
To declare an ArrayList, the syntax looks like this:
To initialize an ArrayList:
After declaring and initializing our ArrayList, we now have a flexible format. To harness the power of the ArrayList, we call in its functions():
size(), add(), subtract(), and get().
Here’s a code example using the 4 functions: get(), size(), add(), and remove().
Study the code closely, especially the comments.
Download and run the above code. Note the interactivity with your mouse and get a feel for the functions() used in this ArrayList.
3. Further Resources
Each future project will be different and depending on your needs you may want to use an ArrayList. The above example gives you an idea of the potential applications and the syntax structure. Here’s a couple more ways to explore ArrayLists.
Jose Sanchez of the Plethora Project presents a simplified tutorial on ArrayLists that is clear and concise.
His book, Learning Processing and his videos also informed this curriculum.
In the following two videos, Shiffman explains why and how to use ArrayLists very well.
One note on these videos is that he covers content not yet presented in the previous tutorials such as enhanced loops. Still it is well worth watching these two videos to get a comprehensive explanation on ArrayLists from this Processing guru.
ArrayLists Part 1
ArrayLists Part 2