On Day 27, we learn about the ArrayList class in Java, which provides a dynamic array that can grow and shrink automatically. Unlike normal arrays, where the size is fixed at creation, ArrayList
adjusts its size as elements are added or removed.
1. Creating an ArrayList
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Create an ArrayList of Strings
ArrayList<String> fruits = new ArrayList<>();
// Add elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Mango");
System.out.println(fruits);
}
}
Explanation: We import java.util.ArrayList
, then create a list of String
objects. The add()
method inserts new items.
2. Accessing and Modifying Elements
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> colors = new ArrayList<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
// Access elements
System.out.println("First color: " + colors.get(0));
// Modify element
colors.set(1, "Yellow");
// Remove element
colors.remove(2);
System.out.println("Updated list: " + colors);
}
}
Explanation: get()
retrieves an element, set()
updates it, and remove()
deletes it.
3. Looping Through an ArrayList
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
// For loop
for (int i = 0; i < numbers.size(); i++) {
System.out.println("Index " + i + ": " + numbers.get(i));
}
// Enhanced for loop
for (int n : numbers) {
System.out.println("Number: " + n);
}
}
}
Explanation: We can loop using a traditional for
loop with size()
or the enhanced for-each
loop.
4. Useful Methods
add(element)
– Add itemget(index)
– Get itemset(index, element)
– Update itemremove(index)
– Remove itemsize()
– Returns list sizeclear()
– Removes all itemscontains(element)
– Checks if item exists
Summary
ArrayList is a dynamic array in Java that makes it easy to store, access, and modify a collection of elements without worrying about fixed sizes.