Java ArrayList
Java ArrayList
Imagine a regular array (the one you've probably learned already). It's like a row of fixed-size
boxes. Once you decide you need 10 boxes, you always have exactly 10 boxes. You can put
things in them, take things out, but you can't suddenly add an 11th box or remove one without
creating a whole new set of boxes.
Key Characteristics:
You can find more details on the W3Schools page: Java ArrayLists
Example 1: Managing a Guest List for an Event (e.g., a Seminar in Rosario, Ilocos Region)
Scenario: You are organizing a seminar or conference. People register online, and you need a
list of attendees. The number of attendees is unknown until registration closes (and might even
change due to cancellations or last-minute sign-ups).
● Flexible Capacity: You don't know if 50 or 500 people will register. ArrayList handles
the varying number of guests.
● Adding new guests: Each time someone registers, you add() their name/details to the
list.
● Removing cancelled guests: If someone cancels, you can remove() them.
● Printing the list: You'll need to iterate through the list to print badges or check people in.
● Ordered list (often alphabetical for ease of finding): You can sort the list by name
using Collections.sort().
Java
import java.util.ArrayList;
import java.util.Collections; // Import the Collections class for sorting
// 3. Access an element
System.out.println("First car in the list: " + cars.get(0));
DSA3
// 4. Modify an element
cars.set(0, "Opel");
System.out.println("ArrayList after modifying first element: " + cars);
// 5. Remove an element
cars.remove(3); // Removes "Mazda" (now at index 3 after "Opel" replaced "Volvo")
System.out.println("ArrayList after removing an element: " + cars);
Alright, let's break down the sample Java program for ArrayLists step-by-step.
import java.util.ArrayList;
import java.util.Collections; // Import the Collections class for sorting
DSA4
import java.util.ArrayList;: This line imports the ArrayList class, which is part of
the java.util package. You need to import it to use ArrayList in your code.
import java.util.Collections;: This line imports the Collections class, also from
the java.util package. We use Collections.sort() to sort our ArrayLists.
public class ArrayListExample { ... }: This defines our main class named
ArrayListExample. All Java programs have at least one class.
public static void main(String[] args) { ... }: This is the main method where
the program execution begins.
ArrayList<String>: This specifies that we are creating an ArrayList that will hold
String objects. The <String> part is called a "type parameter" or "generics," and it ensures
that this ArrayList can only store String objects, preventing common errors.
cars.add("Volvo");: The add() method is used to insert elements into the ArrayList. By
default, add() appends the new element to the end of the list. We add "Volvo", "BMW", "Ford",
and "Mazda".
DSA5
// 3. Access an element
System.out.println("First car in the list: " + cars.get(0));
cars.get(0): The get() method is used to retrieve an element at a specific index. ArrayLists
are zero-indexed, meaning the first element is at index 0, the second at 1, and so on. This line
will print "Volvo".
// 4. Modify an element
cars.set(0, "Opel");
System.out.println("ArrayList after modifying first element: " + cars);
// 5. Remove an element
cars.remove(3); // Removes "Mazda" (now at index 3 after "Opel" replaced "Volvo")
System.out.println("ArrayList after removing an element: " + cars);
cars.remove(3);: The remove() method is used to delete an element. You can remove by
index (as shown here) or by specifying the object itself. In this case, "Mazda" (which moved to
index 3 after "Volvo" was replaced) is removed. When an element is removed, the size of the
ArrayList decreases, and subsequent elements shift to fill the gap.
cars.size(): The size() method returns the number of elements currently in the
ArrayList.
for (String i : cars) { ... }: This is an enhanced for loop (or "for-each loop"). It's a
convenient way to iterate over each element in a collection.
DSA6
● String i: Declares a variable i of type String which will temporarily hold each
element during the iteration.
● : cars: Specifies the ArrayList to iterate over.
● In each iteration, i will take on the value of the next element in cars.
for (int i = 0; i < cars.size(); i++) { ... }: This is a traditional for loop.
This section demonstrates using an ArrayList to store Integer objects. Remember that
ArrayLists store objects, not primitive data types directly. Integer is the wrapper class for
the primitive int.
Collections.sort(myNumbers);: When used with an ArrayList of Integer (or other
numeric wrapper classes like Double, Float), sort() will arrange the elements in ascending
numerical order.
cars.clear();: The clear() method removes all elements from the ArrayList, making it
empty.
This program covers the fundamental operations you'll perform with ArrayLists in Java. It's a
powerful and flexible data structure for managing collections of objects where the size can
change during program execution.
Scenario: When you're shopping online, you add items to your cart. You don't know beforehand
how many items a customer will buy. They might buy 1 item, 5 items, or 50 items.
● Dynamic items: The number of items in the cart changes constantly. A fixed-size array
wouldn't work because you'd either run out of space or waste a lot of space.
● Adding items: Each time a user clicks "Add to Cart," you use cart.add(item);.
● Removing items: If a user changes their mind, you use cart.remove(item); or
cart.remove(index);.
● Viewing items: To display the cart contents, you iterate through the ArrayList.
● Order matters: The order in which items are added might be relevant (e.g., for display
purposes, or if there's a "recently added" feature).
DSA8
Code Sketch:
import java.util.ArrayList;
class Product {
String name;
double price;
// Constructor, getters, etc.
public Product(String name, double price) {
this.name = name;
this.price = price;
}
@Override
public String toString() {
return name + " (₱" + String.format("%.2f", price) + ")";
}
}
Example 2: Managing a Guest List for an Event (e.g., a Seminar in Rosario, Ilocos Region)
Scenario: You are organizing a seminar or conference. People register online, and you need a
list of attendees. The number of attendees is unknown until registration closes (and might even
change due to cancellations or last-minute sign-ups).
● Flexible Capacity: You don't know if 50 or 500 people will register. ArrayList handles
the varying number of guests.
● Adding new guests: Each time someone registers, you add() their name/details to the
list.
● Removing cancelled guests: If someone cancels, you can remove() them.
● Printing the list: You'll need to iterate through the list to print badges or check people in.
● Ordered list (often alphabetical for ease of finding): You can sort the list by name
using Collections.sort().
Code Sketch:
import java.util.ArrayList;
import java.util.Collections; // For sorting
// Guests register
guestNames.add("Juan Dela Cruz");
guestNames.add("Maria Santos");
guestNames.add("Pedro Reyes");
guestNames.add("Anna Gomez");
guestNames.add("Jose Rizal");
// Someone cancels
System.out.println("Cancellation: Jose Rizal");
guestNames.remove("Jose Rizal"); // Remove by object
DSA10