ARRL - Intro to ArrayLists (Lesson)

APCompSci_LessonTopBanner.png

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.

ArrayList Class
Column 1 int size () Column 2 Returns the number of elements in the list
Column 1 boolean add(E obj) Column 2 Appends obj to end of list; returns true
Column 1 void add(int index, E obj) Column 2 Inserts obj at position index (0 <= index <= size), moving elements at position index and higher to the right(adds 1 to their indices) and adds 1 to size
Column 1 E get (int index) Column 2 Returns the element at position index in the list
Column 1 E set(int index, E obj) Column 2 Replaces the element at position index with obj; returns the element formerly at position index
Column 1 E remove(int index) Column 2 Removes element from position index, moving elements at position index + 1 and higher to the left(subtracts 1 from their indices) and subtracts 1 from size; returns the element formerly at position index 

Creating an ArrayList

ArrayList1 myStuff = new 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.

ArrayList<Type> myList = new ArrayLIst<Type> ( ) ;

The word Type would be replaced with String or any other object type that your ArrayList may contain.

 ArrayList<String> friends = new ArrayList<String> ( ) ; 

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.

Integer num = new Integer (1) ; 

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:

int x = num.intValue ( ) ; 

The other Wrapper classes that you may use are Double for double and Boolean for boolean.

Book Icon 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 Icon 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

APCompSci_LessonBottomBanner.pngIMAGES CREATED BY GAVS