ARRL - Intro to ArrayLists (Lesson)
Intro to ArrayLists
Introduction
An ArrayList is very similar to an array, however, it can only collect objects unlike arrays which can also hold primitive data. They can grow or shrink as needed. ArrayList is a class, which is why it is capitalized. The ArrayList class has a constructor and methods for many useful tasks. The Java Quick Reference includes information about the ArrayList class that will be helpful during the AP Exam.
Creating an ArrayList
Notice in the above line of code we do not know what type of data is being stored in the ArrayList. When we try to remove elements, we will need to typecast them as a specific object. It may be more helpful for us to declare the type when the ArrayList is created.
The word Type would be replaced with String or any other object type that your ArrayList may contain.
These examples use the ArrayList constructor which construct an empty list.
Wrapper Classes
Since ArrayLists will only store objects we need to find a way to use primitive data. This is where the Wrapper class comes into play. The Wrapper class makes primitive data into objects.
The variable num is now declared and created as an Integer storing 1. To unwrap the 1 and assign it to an int we would do the following:
The other Wrapper classes that you may use are Double for double and Boolean for boolean.
Click on "Runestone Academy" below to open the required reading that is listed.
Runestone Academy: AP CSA – Java Review Links to an external site.:
READ: 9.7 – The ArrayList Class
Practice It
Practice-It! Practice
1. Go to the PracticeIt website Links to an external site..
2. Log into account.
3. Click on Start Practicing!
4. Go to the most recent edition.
5. Click on Chapter 10: ArrayLists
6. Complete Self-Check: 10.2
IMAGES CREATED BY GAVS