Java Learner logo

Module 7: Arrays and the Collections Framework

Lesson focus

Introduction to ArrayList

Step up from arrays to `ArrayList`, a dynamic, resizable array implementation from the Collections Framework.

Why ArrayList? Arrays are great, but their fixed size is a major limitation. You can't add or remove elements after an array has been created. ArrayList solves this problem.

What is ArrayList? ArrayList is a class from the Java Collections Framework that represents a resizable array. It stores elements in a list that can grow and shrink dynamically as you add or remove elements.

Creating an ArrayList: List<String> names = new ArrayList<>();

  • Generics (<String>): The part in the angle brackets is called a generic type parameter. It tells the ArrayList what type of objects it will hold. This provides compile-time type safety.
  • Programming to the Interface: It is a best practice to declare the variable as the interface type (List) and initialize it with a specific implementation (ArrayList). This makes your code more flexible.

Key ArrayList Methods:

  • add(element): Adds an element to the end of the list.
  • get(index): Retrieves the element at a specific index.
  • set(index, element): Replaces the element at a specific index.
  • remove(index) or remove(object): Removes an element.
  • size(): Returns the number of elements in the list.
  • isEmpty(): Checks if the list is empty.
  • clear(): Removes all elements.

Mini-Exercise: Create an ArrayList of Double to store a list of prices. Add a few prices, then remove one, and finally, loop through the list to print all the remaining prices.

import java.util.ArrayList;
import java.util.List;

List<String> tasks = new ArrayList<>();

// Add items
tasks.add("Buy milk");
tasks.add("Walk the dog");

// Access an item
String firstTask = tasks.get(0);

// Remove an item
tasks.remove(1);

System.out.println("Tasks to do: " + tasks); // Tasks to do: [Buy milk]

Lesson quiz

What is the main advantage of `ArrayList` over a standard array?

Next lesson →