ArrayList Basics in Java
Problem
ArrayList is a resizable list implementation that lets you add, remove, and access elements by index.
Add elements to an ArrayList, remove one, and print what remains.
Java Program
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
fruits.remove("Banana"); // removes by value, not by index
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}Output
Core Logic
ArrayList makes this easy — add a few elements, remove one by value, and loop over what's left.
- 1
new ArrayList<String>()creates an empty, resizable list. - 2
add()appends each new element to the end of the list. - 3
remove("Banana")searches for the first matching element and deletes it, shifting later elements down by one index. - 4The enhanced for-loop walks the remaining elements in their current order.
Apple and Cherry.Key Point: remove() here takes the object value, not an index — remove(1) would instead delete by position.
Key Concepts
Approach 2: removeIf() with a Lambda
import java.util.ArrayList;
public class ArrayListDemoRemoveIf {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Removes every element matching the lambda condition
fruits.removeIf(fruit -> fruit.equals("Banana"));
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
Output
Core Logic
removeIf() offers a different way to delete — hand it a lambda condition instead of an exact value to match.
- 1
fruits.removeIf(fruit -> fruit.equals("Banana"))takes aPredicate<String>— a lambda that returnstruefor elements to remove. - 2Internally,
removeIf()walks the list and deletes every element the predicate matches, which can be more than one. - 3The rest of the program — building the list with
add()and printing with a for-each loop — stays the same.
removeIf(fruit -> fruit.equals("Banana")) removes "Banana", leaving Apple and Cherry, same as the direct remove("Banana") call.Key Point: Unlike remove(Object), which deletes only the first match, removeIf() removes every element matching the condition — useful when a value might appear more than once in the list.
Key Concepts
Interview Questions
What is the default capacity of an ArrayList?
An empty ArrayList allocates its first internal array of 10 slots on the first add, then grows by about 50% whenever it fills up.
Why does list.remove(1) remove an element at index 1 instead of the value 1?
For a List<Integer>, remove(int) removes by index. To remove the value, call remove(Integer.valueOf(1)).