0% found this document useful (0 votes)
4 views10 pages

Java ArrayList

An ArrayList in Java is a dynamic, resizable array that allows for flexible storage of objects, unlike fixed-size arrays. It supports core operations such as adding, accessing, modifying, and removing elements, and can handle varying numbers of items, making it ideal for scenarios like managing guest lists or shopping carts. The document provides examples and code snippets demonstrating the creation and manipulation of ArrayLists.

Uploaded by

bernardmarcella1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views10 pages

Java ArrayList

An ArrayList in Java is a dynamic, resizable array that allows for flexible storage of objects, unlike fixed-size arrays. It supports core operations such as adding, accessing, modifying, and removing elements, and can handle varying numbers of items, making it ideal for scenarios like managing guest lists or shopping carts. The document provides examples and code snippets demonstrating the creation and manipulation of ArrayLists.

Uploaded by

bernardmarcella1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

DSA1

What is an ArrayList? (A Quick Recap)

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.

An ArrayList in Java is like a dynamic, resizable array. An ArrayList is a resizable array,


unlike built-in arrays which have a fixed size. Think of it as a magical box that automatically
grows when you put more stuff in it than it can hold, and shrinks when you take stuff out. You
don't have to worry about managing the underlying "boxes" (memory) yourself. It's built on top of
a regular array, but it handles the resizing behind the scenes.

Key Characteristics:

●​ Dynamic Size: It can grow or shrink as needed.


●​ Ordered Collection: Elements are stored in the order they are added, and you can
access them by their index (position).
●​ Allows Duplicates: You can add the same element multiple times.
●​ Stores Objects: It can only store objects (e.g., String, Integer, Student objects),
not primitive data types directly. For primitives, you use their wrapper classes (Integer
for int, Double for double, etc.).
●​ Part of java.util package: You need to import java.util.ArrayList;.
●​ Package and Interface: ArrayLists are part of the java.util package and implement
the List interface.
●​ Dynamic Elements: They allow for dynamic addition and removal of elements.
●​ Core Operations:
○​ Create: How to create an ArrayList object.
○​ Add: Adding elements (at the end or a specified index).
○​ Access: Using get() to access elements.
○​ Modify: Using set() to change elements.
○​ Remove: Using remove() or clear() to delete elements.
○​ Size: Determining the size with size().
●​ Iteration: Looping through elements using both traditional for loops and enhanced
for-each loops.
●​ Primitive Types: ArrayLists store objects, so for primitive types (like int), their
corresponding wrapper classes (e.g., Integer) must be used.
●​ Sorting: Demonstrates how to sort ArrayLists alphabetically or numerically using the
Collections.sort() method from the java.util.Collections class.
●​ Flexibility: Briefly touches upon declaring ArrayLists using the List interface for
greater flexibility.
DSA2

You can find more details on the W3Schools page: Java ArrayLists

Real-World Examples of ArrayList Usage

Let's look at scenarios where an ArrayList would be the perfect choice:

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).

Why ArrayList is perfect:

●​ 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 ArrayList Implementation

Java

import java.util.ArrayList;
import java.util.Collections; // Import the Collections class for sorting

public class ArrayListExample {


public static void main(String[] args) {
// 1. Create an ArrayList of Strings
ArrayList<String> cars = new ArrayList<String>();
System.out.println("Initial ArrayList: " + cars);

// 2. Add elements to the ArrayList


cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println("ArrayList after adding elements: " + cars);

// 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);

// 6. Get the size of the ArrayList


System.out.println("Size of the ArrayList: " + cars.size());

// 7. Loop through the ArrayList using a for-each loop


System.out.println("\nCars in the ArrayList (for-each loop):");
for (String i : cars) {
System.out.println(i);
}

// 8. Loop through the ArrayList using a traditional for loop


System.out.println("\nCars in the ArrayList (traditional for loop):");
for (int i = 0; i < cars.size(); i++) {
System.out.println(cars.get(i));
}

// 9. Sort the ArrayList alphabetically


Collections.sort(cars); // Sort cars alphabetically
System.out.println("\nArrayList after alphabetical sort: " + cars);

// Example with Integer ArrayList


ArrayList<Integer> myNumbers = new ArrayList<Integer>();
myNumbers.add(33);
myNumbers.add(15);
myNumbers.add(20);
myNumbers.add(34);
myNumbers.add(8);
myNumbers.add(12);

// Sort the Integer ArrayList numerically


Collections.sort(myNumbers); // Sort myNumbers numerically
System.out.println("Integer ArrayList after numerical sort: " + myNumbers);

// 10. Clear all elements from the ArrayList


cars.clear();
System.out.println("ArrayList after clearing all elements: " + 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 {


public static void main(String[] args) {

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.

// 1. Create an ArrayList of Strings


ArrayList<String> cars = new ArrayList<String>();
System.out.println("Initial ArrayList: " + cars);

ArrayList<String> cars = new ArrayList<String>();: This is how you declare and


initialize an ArrayList.

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: This is the name of our ArrayList variable.

new ArrayList<String>(): This creates a new, empty ArrayList object in memory.

System.out.println("Initial ArrayList: " + cars);: This prints the initial state of


the ArrayList, which will be [] (an empty list).

// 2. Add elements to the ArrayList


cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println("ArrayList after adding elements: " + cars);

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

The println statement shows the list after these additions.

// 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);

cars.set(0, "Opel");: The set() method is used to update an element at a specified


index. It takes two arguments: the index of the element to change and the new value. Here,
"Volvo" at index 0 is replaced with "Opel".

// 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.

// 6. Get the size of the ArrayList


System.out.println("Size of the ArrayList: " + cars.size());

cars.size(): The size() method returns the number of elements currently in the
ArrayList.

// 7. Loop through the ArrayList using a for-each loop


System.out.println("\nCars in the ArrayList (for-each loop):");
for (String i : cars) {
System.out.println(i);
}

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.

// 8. Loop through the ArrayList using a traditional for loop


System.out.println("\nCars in the ArrayList (traditional for loop):");
for (int i = 0; i < cars.size(); i++) {
System.out.println(cars.get(i));
}

for (int i = 0; i < cars.size(); i++) { ... }: This is a traditional for loop.

●​ int i = 0: Initializes a counter variable i to 0.


●​ i < cars.size(): The loop continues as long as i is less than the current size of the
ArrayList.
●​ i++: Increments i after each iteration.
●​ Inside the loop, cars.get(i) is used to access each element by its index.

// 9. Sort the ArrayList alphabetically


Collections.sort(cars); // Sort cars alphabetically
System.out.println("\nArrayList after alphabetical sort: " + cars);

Collections.sort(cars);: The static sort() method from the Collections class is


used to sort the elements of an ArrayList. For String objects, it sorts alphabetically.

// Example with Integer ArrayList


ArrayList<Integer> myNumbers = new ArrayList<Integer>();
myNumbers.add(33);
myNumbers.add(15);
myNumbers.add(20);
myNumbers.add(34);
myNumbers.add(8);
myNumbers.add(12);

// Sort the Integer ArrayList numerically


Collections.sort(myNumbers); // Sort myNumbers numerically
System.out.println("Integer ArrayList after numerical sort: " + myNumbers);
DSA7

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.

// 10. Clear all elements from the ArrayList


cars.clear();
System.out.println("ArrayList after clearing all elements: " + cars);
}
}

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.

Real-World Examples of ArrayList Usage

Let's look at scenarios where an ArrayList would be the perfect choice:

Example 1: A Shopping Cart (Online Store)

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.

Why ArrayList is perfect:

●​ 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) + ")";
}
}

public class ShoppingCart {


public static void main(String[] args) {
ArrayList<Product> cart = new ArrayList<>(); // Our shopping cart

// Customer adds items


cart.add(new Product("Laptop", 45000.00));
cart.add(new Product("Wireless Mouse", 850.00));
cart.add(new Product("Keyboard", 1500.00));
cart.add(new Product("Laptop Bag", 1200.00));

System.out.println("--- Your Shopping Cart ---");


for (Product item : cart) {
System.out.println("- " + item);
}

// Customer removes an item (e.g., the mouse)


System.out.println("\nRemoving Wireless Mouse...");
// This assumes a equals method in Product or relies on object identity
// For simplicity, let's remove by index if we know its position, or iterate to find
// A more robust solution would find the product object and then remove it.
cart.remove(1); // Assuming Wireless Mouse is at index 1

System.out.println("\n--- Updated Shopping Cart ---");


for (Product item : cart) {
System.out.println("- " + item);
}

System.out.println("\nTotal items in cart: " + cart.size());


}
}
DSA9

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).

Why ArrayList is perfect:

●​ 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

public class SeminarGuestList {


public static void main(String[] args) {
ArrayList<String> guestNames = new ArrayList<>();

System.out.println("--- Seminar Registration ---");

// Guests register
guestNames.add("Juan Dela Cruz");
guestNames.add("Maria Santos");
guestNames.add("Pedro Reyes");
guestNames.add("Anna Gomez");
guestNames.add("Jose Rizal");

System.out.println("Initial Guest List:");


for (String name : guestNames) {
System.out.println("- " + name);
}

// A new guest registers late


System.out.println("\nLate registration: Sarah Lim");
guestNames.add("Sarah Lim");

// Someone cancels
System.out.println("Cancellation: Jose Rizal");
guestNames.remove("Jose Rizal"); // Remove by object
DSA10

System.out.println("\n--- Final Guest List (Unsorted) ---");


for (String name : guestNames) {
System.out.println("- " + name);
}

// Prepare for check-in: sort alphabetically


Collections.sort(guestNames);

System.out.println("\n--- Final Guest List (Sorted for Check-in) ---");


for (String name : guestNames) {
System.out.println("- " + name);
}

System.out.println("\nTotal confirmed attendees: " + guestNames.size());


}
}

You might also like