An ArrayList is a dynamic array that can grow and shrink in size as you add or remove elements. Unlike regular arrays (which have a fixed size), ArrayLists automatically resize themselves when needed.
Think of an ArrayList like a flexible list - you can add items to the end, insert them in the middle, remove them, and the list adjusts its size automatically.
String[] array = new String[3]; // Fixed size of 3
array[0] = "Apple";
array[1] = "Banana";
array[2] = "Cherry";
// Can't add more items - size is fixed!ArrayList<String> list = new ArrayList<>(); // Dynamic size
list.add("Apple");
list.add("Banana");
list.add("Cherry");
list.add("Date"); // Can keep adding items!
list.add("Elderberry");import java.util.ArrayList;
// Create empty ArrayList
ArrayList<String> fruits = new ArrayList<>();
ArrayList<Integer> numbers = new ArrayList<>();
// With initial capacity (optional optimization)
ArrayList<String> bigList = new ArrayList<>(100);ArrayLists use generics to specify what type of objects they hold:
ArrayList<String>- holds StringsArrayList<Integer>- holds IntegersArrayList<Boolean>- holds Booleans
ArrayList<String> list = new ArrayList<>();
// Add to end
list.add("First"); // [First]
list.add("Second"); // [First, Second]
// Add at specific position
list.add(1, "Middle"); // [First, Middle, Second]
// Add at beginning
list.add(0, "Start"); // [Start, First, Middle, Second]int size = list.size(); // Number of elements
boolean isEmpty = list.isEmpty(); // true if no elements// Get element at index (0-based)
String first = list.get(0); // First element
String last = list.get(list.size() - 1); // Last element
// Check bounds first to avoid IndexOutOfBoundsException
if (index >= 0 && index < list.size()) {
String item = list.get(index);
}// Check if contains element
boolean hasApple = list.contains("Apple");
// Find position of element
int position = list.indexOf("Apple"); // -1 if not found
// Find last occurrence
int lastPos = list.lastIndexOf("Apple");// Remove by index
String removed = list.remove(0); // Remove first element
// Remove by value (removes first occurrence)
boolean wasRemoved = list.remove("Apple");
// Remove all elements
list.clear();// Replace element at index
list.set(0, "New Value"); // Changes element at position 0ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Or use Collections.addAll
Collections.addAll(fruits, "Date", "Elderberry", "Fig");// Using traditional for loop
for (int i = 0; i < list.size(); i++) {
String item = list.get(i);
System.out.println(item);
}
// Using enhanced for loop (for-each)
for (String item : list) {
System.out.println(item);
}public String findLongest(ArrayList<String> list) {
if (list.isEmpty()) return null;
String longest = list.get(0);
for (String item : list) {
if (item.length() > longest.length()) {
longest = item;
}
}
return longest;
}// Shallow copy (recommended)
ArrayList<String> copy = new ArrayList<>(original);
// Alternative method
ArrayList<String> copy2 = (ArrayList<String>) original.clone();// To Object array
Object[] objArray = list.toArray();
// To specific type array
String[] stringArray = list.toArray(new String[0]);| Method | Description | Example |
|---|---|---|
add(item) |
Add to end | list.add("Apple") |
add(index, item) |
Add at position | list.add(0, "First") |
get(index) |
Get element | list.get(2) |
set(index, item) |
Replace element | list.set(1, "New") |
remove(index) |
Remove by index | list.remove(0) |
remove(item) |
Remove by value | list.remove("Apple") |
size() |
Get size | list.size() |
isEmpty() |
Check if empty | list.isEmpty() |
contains(item) |
Check if contains | list.contains("Apple") |
indexOf(item) |
Find position | list.indexOf("Apple") |
clear() |
Remove all | list.clear() |
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
int sum = 0;
for (int num : numbers) {
sum += num;
}// You'll learn this later, but here's a preview:
ArrayList<Person> people = new ArrayList<>();
// person objects would go hereArrayList<String> list = new ArrayList<>();
// String item = list.get(0); // IndexOutOfBoundsException!
// Safe approach:
if (!list.isEmpty()) {
String item = list.get(0);
}// Dangerous - can cause ConcurrentModificationException
for (String item : list) {
if (item.equals("Remove")) {
list.remove(item); // Don't do this!
}
}
// Safe approach - iterate backwards
for (int i = list.size() - 1; i >= 0; i--) {
if (list.get(i).equals("Remove")) {
list.remove(i);
}
}// Dangerous
public int getSize(ArrayList<String> list) {
return list.size(); // NullPointerException if list is null!
}
// Safe
public int getSize(ArrayList<String> list) {
return (list == null) ? 0 : list.size();
}// Bad - no type safety
ArrayList list = new ArrayList(); // Raw type
list.add("String");
list.add(123); // Compiler won't catch this error
// Good - type safe
ArrayList<String> list = new ArrayList<>(); // Generic type
list.add("String");
// list.add(123); // Compiler error - good!- Add to end: O(1) average, O(n) worst case (when resize needed)
- Add at position: O(n) - needs to shift elements
- Get by index: O(1) - direct access
- Remove by index: O(n) - needs to shift elements
- Search (contains): O(n) - linear search
- Good for: Frequent additions to end, random access by index, iteration
- Less good for: Frequent insertions/deletions in middle, searching without index
- Basic Operations: add(), get(), size(), isEmpty()
- Safe Access: Check bounds and null before accessing
- Iteration: Both traditional and enhanced for loops
- Searching: contains(), indexOf(), counting occurrences
- Modification: set(), remove(), clear()
- Conversion: toArray(), copying lists
- Generics: Always specify the type (ArrayList)
ArrayLists are used everywhere:
- Shopping Lists: Add/remove items dynamically
- User Collections: Lists of users, products, orders
- Data Processing: Collecting results from calculations
- Menu Systems: Dynamic menu items
- File Processing: Storing lines read from files
- Game Development: Lists of players, items, scores
- Always Use Generics:
ArrayList<String>notArrayList - Check Bounds: Verify index is valid before accessing
- Handle Null: Check if ArrayList itself is null
- Use Enhanced For: Cleaner code when just iterating
- Consider Performance: Adding to middle is slow for large lists
- Use Meaningful Names:
students,orders,itemsnotlist1,list2
- ArrayList: Dynamic array, good for indexed access
- LinkedList: Good for frequent insertions/deletions
- HashSet: No duplicates, fast searching
- HashMap: Key-value pairs
For now, focus on ArrayList - it's the most commonly used collection in Java!
Remember: ArrayList is like a flexible array that grows and shrinks automatically. Master the basic operations, always handle edge cases, and you'll be able to work with dynamic collections of data effectively!