ArrayLists
An ArrayList
object is like a normal array, but on steroids. It overcomes some of the shortfalls of arrays, such as having to predetermine its size. It adds several useful functions to make its data easy to manage and it is used by many classes in the Android API. This last point means that we need to use ArrayList
if we want to use certain parts of the API. In Chapter 16, Adapters and Recyclers, we will put ArrayList
to work for real. First the theory.
Let's take a look at some code that uses ArrayList
:
// Declare a new ArrayList called myList // to hold Int variables val myList: ArrayList<Int> // Initialize myList ready for use myList = ArrayList()
In the preceding code, we declared and initialized a new ArrayList
object called myList
. We can also do this in a single step, as demonstrated by the following code:
val myList: ArrayList<Int> = ArrayList()
So far, this is not particularly interesting, so let's take a look at what we can actually do with ArrayList...