Java ArrayList Cheat Sheet
Creating an ArrayList
ArrayList<Type> list = new ArrayList<>();
ArrayList<Type> list = new ArrayList<>(initialCapacity);
ArrayList<Type> list = new ArrayList<>(otherList);
Adding Elements
list.add(element); // Add at end
list.add(index, element); // Add at specific position
list.addAll(otherList); // Add all from another list
list.addAll(index, otherList); // Add all at index
Accessing Elements
list.get(index); // Get element at index
list.size(); // Number of elements
list.isEmpty(); // Check if empty
Modifying Elements
list.set(index, element); // Replace element at index
Removing Elements
list.remove(index); // Remove element at index
list.remove(Object o); // Remove first occurrence
list.removeAll(otherList); // Remove all from another list
list.clear(); // Remove all elements
Searching / Checking
list.contains(element); // Check presence
list.indexOf(element); // First index of element
list.lastIndexOf(element); // Last index of element
Iteration
for (Type x : list) { ... } // For-each loop
Iterator<Type> it = list.iterator(); // Using iterator
Conversion
list.toArray(); // Convert to Object[]
list.toArray(new Type[0]); // Convert to Type[]
Sorting & Reversing
Collections.sort(list); // Ascending sort
list.sort(comparator); // Custom sort
Collections.reverse(list); // Reverse list
Java ArrayList Cheat Sheet
Utility Methods
Collections.swap(list, i, j); // Swap elements
Collections.shuffle(list); // Shuffle list
Collections.copy(dest, src); // Copy src to dest
Collections.frequency(list, value); // Count occurrences
Example Snippet
ArrayList<Integer> nums = new ArrayList<>();
nums.add(5);
nums.add(2);
nums.add(9);
Collections.sort(nums); // [2, 5, 9]
Collections.reverse(nums); // [9, 5, 2]