Course outline · 0% complete

0/29 lessons0%

Course overview →

ArrayList

lesson 7-1 · ~6 min · 19/29

Quiz

Warm-up from lesson 3-3: you declared int[] scores = {90, 72, 88}. What can this array never do?

ArrayList: the growable list

Arrays (lesson 3-3) have a hard limitation: the size is fixed at creation, but real data rarely announces its size in advance — rows returned by a database, lines in a file, tasks a user keeps adding. Working around it by hand means allocating a bigger array and copying everything over each time you outgrow it. ArrayList is that workaround done for you, and it is the single most-used collection in Java code. It is Java's version of the Python list. It lives in java.util, so the file starts with an import:

import java.util.ArrayList;

ArrayList<String> tasks = new ArrayList<>();
tasks.add("write code");   // append
tasks.get(0)               // read by index
tasks.set(0, "plan")       // replace by index
tasks.remove(1)            // delete by index
tasks.size()               // length
tasks.contains("plan")     // membership test

The <String> is a type parameter: this list holds Strings and nothing else, checked at compile time. Adding an int to it will not compile. Printing an ArrayList shows [a, b, c], much friendlier than arrays.

Code exercise · java

Run this ArrayList tour: add, size, get, contains, remove. Note the import line above the class.

Lists of numbers

Type parameters must be object types, so primitive int is not allowed. Use the wrapper class Integer (Double for double, Boolean for boolean, Character for char):

ArrayList<Integer> scores = new ArrayList<>();
scores.add(90);        // int auto-wraps into Integer
int first = scores.get(0);  // and unwraps back

The automatic wrapping is called autoboxing. You mostly never notice it, except in one trap: scores.remove(1) removes index 1, while scores.remove(Integer.valueOf(90)) removes the value 90.

The enhanced for from lesson 3-3 works on any collection: for (String t : tasks).

Array or ArrayList?

Both hold an ordered sequence, so which do you reach for? The deciding question is whether the size changes:

ArrayArrayList
Sizefixed at creationgrows and shrinks
Lengtha.lengthlist.size()
Reada[0]list.get(0)
Element typesprimitives or objectsobjects only (Integer, not int)

Default to ArrayList — nearly all application code does, because data changes. Arrays remain the right call when the size is truly fixed and known (new int[26] for letter counts) or in performance-critical numeric code, since primitives in an array avoid the wrapper objects the next section introduces. Interview problems hand you arrays constantly, so you will keep using both.

Code exercise · java

Your turn. Build an ArrayList<Integer> with 90, 72, 88, then add 100, then remove the element at index 1. Print the list, then loop over it to total the scores and print `sum: 278`.