☕ Java

ArrayList in Java

ArrayList is a resizable array — it grows as you add elements and shrinks as you remove them. It's the most used collection in Java, and for good reason: it combines the speed of arrays with the flexibility of dynamic sizing.

ArrayList Basics — Your Go-To Dynamic List

Regular arrays in Java have a fixed size — you declare int[10] and you're stuck with 10 slots. ArrayList removes that limitation. It starts at a default capacity and automatically resizes when you need more space. When to use ArrayList: • You need a list that grows or shrinks at runtime • You need fast random access (get any element by index instantly) • Order of insertion matters • Duplicates are allowed
Java
import java.util.ArrayList;
import java.util.Collections;

ArrayList<String> cart = new ArrayList<>();

// Add items
cart.add("Laptop");
cart.add("Mouse");
cart.add("Keyboard");
cart.add(1, "Monitor");  // Insert at specific index

System.out.println(cart);        // [Laptop, Monitor, Mouse, Keyboard]
System.out.println(cart.get(0)); // Laptop — access by index
System.out.println(cart.size()); // 4

// Remove
cart.remove("Mouse");            // by value
cart.remove(0);                  // by index — removes "Laptop"

// Check
System.out.println(cart.contains("Keyboard")); // true
System.out.println(cart.isEmpty());            // false

// Sort alphabetically
Collections.sort(cart);
System.out.println(cart);  // [Keyboard, Monitor]

Iterating — Three Ways

For-each is cleanest for reading. Use a classic for loop if you need the index. Use streams (Java 8+) for filtering/transforming.
Java
ArrayList<Integer> prices = new ArrayList<>();
prices.add(1200); prices.add(450); prices.add(875);

// 1. For-each — cleanest for simple iteration
for (int price : prices) {
    System.out.println("Price: ₹" + price);
}

// 2. Index-based for loop — when you need the position
for (int i = 0; i < prices.size(); i++) {
    System.out.println("Item " + i + ": ₹" + prices.get(i));
}

// 3. Java 8 forEach with lambda — expressive and concise
prices.forEach(p -> System.out.println("₹" + p));

// 4. Remove while iterating — use Iterator to avoid ConcurrentModificationException
Iterator<Integer> it = prices.iterator();
while (it.hasNext()) {
    if (it.next() < 500) it.remove();  // safe removal during iteration
}