Skip to main content
Logo image

Chapter 10 ArrayLists

In Chapter 6 Arrays we learned about arrays, as our first data type that we can use to hold multiple values. However arrays are not very flexible. Most notably, the size of an array is established at the time of creation and cannot be changed. What are we supposed to do if we want to collect an unknown number of objects. Or if we want to both add and remove items from a collection? For example, if we wanted to represent a shopping list, we might add to the list throughout the week and remove things from the list while we are shopping. We wouldn’t want to have to guess when we first made our shopping list at the beginning of the week how many things we were going to put in it.
For cases like this, Java has a class called ArrayList which is a resizable list. It is called ArrayList because it stores the items that have been added to it in an underlying array. But it also takes care of keeping track of how many items have been added to the array and it will create a new bigger array under the covers when needed to hold more items. If you’ve used other languages like Javascript, Python, or Snap! an ArrayList is much more like the lists and arrays in those languages than Java’s arrays are.
In this chapter we’ll look at how to make and use ArrayLists and also look at something called wrapper classes that exist to bridge the gap between Java’s primitive types and arrays and classes like ArrayList. Then we’ll review how to apply loop contstructs and loop based algorithms that we’ve used with arrays and Strings to ArrayLists plus a few new algorithms that only apply to ArrayLists since they are resizable.