Home » Java Tutorial » ArrayList Methods in Java with Examples & Explanations

ArrayList Methods in Java with Examples & Explanations

Support this post with a reaction:

3,385 views

ArrayList in Java is one of the most used classes in the Java Collections Framework. It allows us to store dynamic arrays that can grow as needed. Below is a comprehensive list of ArrayList methods, categorized and explained with clear examples, so you can understand and use them efficiently in real-world applications.

Here are the ArrayList Methods in Java

1. add(E e)

Description: Appends the specified element to the end of the list.

Detailed Explanation:

  • This method takes a single argument of the type E, which is the type of elements stored in the ArrayList.
  • It adds the element to the end of the list, increasing the list’s size by 1.
  • Internally, if the array is full, a new array with a larger capacity is created and the existing elements are copied over.
  • It returns true as specified by the Collection interface.

Use Case: Useful when you want to add new elements dynamically without worrying about array size.

ArrayList<String> colors = new ArrayList<>();
colors.add("Red");
colors.add("Blue");
System.out.println(colors); // [Red, Blue]

🔍 Best used in loops or when appending values conditionally.

2. add(int index, E element)

Description: Inserts the specified element at the specified position in the list.

Detailed Explanation:

  • Takes two arguments: an index and the element to insert.
  • It shifts the element currently at that position and any subsequent elements to the right.
  • Throws IndexOutOfBoundsException if index is negative or greater than size.

Use Case: Insert items at a specific position in an ordered list.

colors.add(1, "Green");
System.out.println(colors); // [Red, Green, Blue]

🔍 Good for maintaining a specific order while inserting new data.

3. addAll(Collection<? extends E> c)

Description: Appends all of the elements in the specified collection to the end of the list.

Detailed Explanation:

  • Takes a collection (like another ArrayList or Set) and adds each element to the list in the same order.
  • Increases the size of the list by the number of elements in the collection.
  • Returns true if the list is modified.

Use Case: Merging or copying one collection into another.

ArrayList<String> extraColors = new ArrayList<>();
extraColors.add("Yellow");
extraColors.add("Purple");

colors.addAll(extraColors);
System.out.println(colors); // [Red, Green, Blue, Yellow, Purple]

🔍 Efficient for combining data from multiple sources.

4. addAll(int index, Collection<? extends E> c)

Description: Inserts all elements from the specified collection at the specified position.

Detailed Explanation:

  • Works like add(int, E) but inserts multiple elements at the given index.
  • Elements originally at the index and beyond are shifted right.
  • Throws IndexOutOfBoundsException for an invalid index.

Use Case: Insert a sublist or batch of elements into a specific portion of another list.

colors.addAll(2, Arrays.asList("Orange", "Pink"));
System.out.println(colors); // [Red, Green, Orange, Pink, Blue, Yellow, Purple]

🔍 Maintains insertion order while integrating multiple elements at a specific point.

5. get(int index)

Description: Returns the element at the specified position.

Detailed Explanation:

  • Takes an integer index and returns the element located at that position in the list.
  • Index starts from 0.
  • Throws IndexOutOfBoundsException if index < 0 or >= size.

Use Case: Access a specific item when the index is known.

String secondColor = colors.get(1);
System.out.println(secondColor); // Green

🔍 Commonly used in loops or when retrieving data based on position.

6. set(int index, E element)

Description: Replaces the element at the specified index with the given element.

Detailed Explanation:

  • Takes an index and a new element.
  • Updates the element at that index with the new one.
  • List size remains the same.
  • Throws IndexOutOfBoundsException if index < 0 or ≥ size.

Use Case: Update an existing item in the list when the index is known.

colors.set(2, "Black");
System.out.println(colors); // [Red, Green, Black, Pink, Blue, Yellow, Purple]

🔍 Common when modifying existing elements based on index (e.g., editing a value in a form or table).

7. remove(int index)

Description: Removes the element at the specified index.

Detailed Explanation:

  • Takes an index and removes the element at that position.
  • List size decreases by 1.
  • Remaining elements shift left to fill the gap.
  • Throws IndexOutOfBoundsException if index < 0 or ≥ size.

Use Case: Delete an item from a known index.

colors.remove(4);
System.out.println(colors); // [Red, Green, Black, Pink, Yellow, Purple]

🔍 Useful in dynamic lists when user deletes an item by index (e.g., “Remove item 4”).

8. remove(Object o)

Description: Removes the first occurrence of the specified object from the list.

Detailed Explanation:

  • Compares using .equals() method.
  • Removes only the first match.
  • Returns true if the item was found and removed; otherwise false.
  • No exception is thrown if the element is not found.

Use Case: Delete a specific value when its position is unknown.

colors.remove("Pink");
System.out.println(colors); // [Red, Green, Black, Yellow, Purple]

🔍 Often used when dealing with values directly (e.g., “remove by name”).

9. clear()

Description: Removes all elements from the list.

Detailed Explanation:

  • Empties the list completely.
  • After this operation, size becomes 0.
  • No exception is thrown.

Use Case: Reset the list to start fresh.

colors.clear();
System.out.println(colors); // []

🔍 Handy when reinitializing or clearing user selections/data.

10. size()

Description: Returns the number of elements in the list.

Detailed Explanation:

  • Returns an int representing the current size of the list.
  • Does not count capacity—only actual elements present.

Use Case: Check how many elements are in the list.

ArrayList<Integer> nums = new ArrayList<>(Arrays.asList(1, 2, 3));
System.out.println(nums.size()); // 3

🔍 Commonly used in loops, validations, or display messages (e.g., “You have 3 items in your cart”).

11. isEmpty()

Description: Checks if the list has no elements.

Detailed Explanation:

  • Returns true if the list size is 0.
  • Returns false if the list has one or more elements.
  • Does not throw any exceptions.

Use Case: Useful for validations before performing actions like iterating or processing the list.

System.out.println(nums.isEmpty()); // false

🔍 Frequently used in conditional checks: if (!list.isEmpty()) { ... }.

12. contains(Object o)

Description: Checks if the specified element exists in the list.

Detailed Explanation:

  • Returns true if the list contains the element.
  • Uses .equals() for comparison.
  • Returns false if the element is not found.

Use Case: Check if a value is present before processing or adding it again.

System.out.println(nums.contains(2)); // true

🔍 Useful in scenarios like avoiding duplicates or checking item availability.

13. indexOf(Object o)

Description: Returns the first index of the specified object.

Detailed Explanation:

  • Returns the index of the first occurrence of the object.
  • Returns -1 if the object is not found.
  • Uses .equals() for comparison.

Use Case: Retrieve the position of a value when duplicates may exist.

System.out.println(nums.indexOf(3)); // 2

Handy when needing the first matching position (e.g., for editing an item).

14. lastIndexOf(Object o)

Description: Returns the last index of the specified object.

Detailed Explanation:

  • Searches from the end of the list.
  • Returns the index of the last match.
  • Returns -1 if the object is not found.

Use Case: Find the last occurrence of a value when duplicates are present.

nums.add(2);
System.out.println(nums.lastIndexOf(2)); // 3

🔍 Useful in removing or analyzing the last duplicate entry.

15. toArray()

Description: Converts the list to an array of type Object[].

Detailed Explanation:

  • Returns a new array containing all elements in the list in the same order.
  • Changes to the returned array do not affect the list and vice versa.

Use Case: When interoperability with array-based APIs or legacy systems is needed.

Object[] arr = nums.toArray();
System.out.println(Arrays.toString(arr));

🔍 Common when needing fixed-size structures or passing data to functions expecting arrays.

16. toArray(T[] a)

Description: Converts the list to a typed array (like Integer[], String[], etc.).

Detailed Explanation:

  • Accepts an array of the desired type.
  • If the given array is large enough, elements are copied into it.
  • If not, a new array of the same type is created.
  • Preserves the order of elements.

Use Case: Use when you need a typed array instead of Object[], especially in type-safe contexts.

Integer[] intArray = nums.toArray(new Integer[0]);
System.out.println(Arrays.toString(intArray)); // [1, 2, 3, 2]

🔍 Prefer this over toArray() when working with generics or avoiding type casting.

17. ensureCapacity(int minCapacity)

Description: Increases the internal capacity of the list to at least the specified minimum.

Detailed Explanation:

  • Internally reserves memory to hold at least minCapacity elements.
  • Helps reduce the cost of resizing when you plan to add many items.
  • Does not change the actual size or content of the list.

Use Case: Pre-allocate space when expecting bulk insertions to improve performance.

ArrayList<String> items = new ArrayList<>();
items.ensureCapacity(100); // Optimize for large additions

🔍 Best used when performance is critical, such as during data import or batch processing.

18. trimToSize()

Description: Trims the internal capacity of the list to its current size.

Detailed Explanation:

  • Frees unused memory if the internal capacity is greater than the actual list size.
  • Useful when the list is finalized, and memory usage needs to be optimized.
  • Does not affect list elements or their order.

Use Case: Minimize memory after large insertions followed by deletions.

items.trimToSize(); // Free unused memory

🔍 Helps reduce memory footprint in memory-constrained environments.

19. clone()

Description: Returns a shallow copy of the ArrayList.

Detailed Explanation:

  • Copies the structure and elements of the list into a new one.
  • It’s a shallow copy, meaning references (not deep copies) are copied for objects.
  • Requires type casting (ArrayList<T>).

Use Case: Create a duplicate list to work with, without modifying the original.

ArrayList<Integer> cloned = (ArrayList<Integer>) nums.clone();
System.out.println(cloned); // [1, 2, 3, 2]

🔍 Useful for backups, undo functionality, or concurrent processing without affecting the original list.

20. iterator()

Description: Returns an Iterator to traverse the list in a forward direction.

Detailed Explanation:

  • Returns an Iterator<T> starting at the beginning of the list.
  • You can use it in a while loop with hasNext() and next() methods.
  • Safe way to iterate without using index-based loops.

Use Case: Traverse list elements when index is not needed or when working with generic collections.

Iterator<Integer> it = nums.iterator();
while (it.hasNext()) {
    System.out.print(it.next() + " ");
}
// Output: 1 2 3 2

🔍 Preferred in frameworks, APIs, and legacy-style Java coding when direct access is restricted.

21. listIterator()

Description: Returns a ListIterator for forward and backward traversal.

Detailed Explanation:

  • Allows navigation in both directions: forward (hasNext, next) and backward (hasPrevious, previous).
  • Can also be used to add, remove, or modify elements during iteration.
  • Starts from index 0 by default.

Use Case: Advanced iteration where you may need to go back or modify items mid-iteration.

ListIterator<Integer> listIt = nums.listIterator();
while (listIt.hasNext()) {
    System.out.print(listIt.next() + " ");
}
// Output: 1 2 3 2

🔍 Ideal for bi-directional navigation or editing elements while looping.

22. subList(int fromIndex, int toIndex)

Description: Returns a view (not a copy) of a portion of the list.

Detailed Explanation:

  • Returns a sublist starting at fromIndex (inclusive) and ending at toIndex (exclusive).
  • The sublist is backed by the original list—modifications affect both.
  • Throws IndexOutOfBoundsException if indices are invalid.

Use Case: Extract a segment of the list for processing.

List<Integer> subList = nums.subList(1, 3);
System.out.println(subList); // [2, 3]

📝 Note: Changes in subList reflect in the original nums list and vice versa.

23. retainAll(Collection<?> c)

Description: Retains only elements in the list that are also in the specified collection.

Detailed Explanation:

  • Removes all elements not present in the given collection.
  • Modifies the original list directly.
  • Returns true if the list changed as a result.

Use Case: Filter the list to only include allowed or required values.

nums.retainAll(Arrays.asList(2));
System.out.println(nums); // [2, 2]

🔍 Useful for filtering or enforcing a whitelist.

24. removeAll(Collection<?> c)

Description: Removes all elements from the list that are present in the specified collection.

Detailed Explanation:

  • Compares using .equals().
  • Modifies the original list.
  • Returns true if any elements were removed.

Use Case: Remove unwanted values in bulk.

nums.removeAll(Arrays.asList(2));
System.out.println(nums); // []

🔍 Helps in cleaning or excluding specific data from a list.

25. equals(Object o)

Description: Checks if two lists are equal (order and elements must match).

Detailed Explanation:

  • Returns true if the other object is a list with the same elements in the same order.
  • Uses .equals() for comparing elements.

Use Case: Compare lists for equality in unit tests or logic comparisons.

ArrayList<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2));
ArrayList<Integer> list2 = new ArrayList<>(Arrays.asList(1, 2));
System.out.println(list1.equals(list2)); // true

🔍 Order matters: [1, 2] is not equal to [2, 1].

26. hashCode()

Description: Returns a hash code value for the list.

Detailed Explanation:

  • Used in hashing structures like HashMap, HashSet, etc.
  • Equal lists will return the same hash code (if equals() is also true).

Use Case: Allow ArrayList to function properly in hash-based collections.

System.out.println(list1.hashCode()); // Example: 994

🔍 Always consistent with equals()—if two lists are equal, their hash codes are too.

27. forEach(Consumer<? super E> action) ✅ (Java 8+)

Description: Performs the given action for each element using a lambda or method reference.

Detailed Explanation:

  • Introduced in Java 8.
  • Takes a lambda expression or method reference as input.
  • Provides a clean, concise way to loop over elements.

Use Case: Iterate with custom logic using functional programming style.

nums = new ArrayList<>(Arrays.asList(5, 10, 15));
nums.forEach(n -> System.out.println(n * 2));
// Output: 10 20 30

🔍 Great for performing actions like logging, mapping, or filtering without traditional loops.

Stream API Integration (Java 8+)

Description: Enables functional-style operations like filtering, mapping, and collecting on collections.

Detailed Explanation:

  • ArrayList and other Collection classes support the stream() method (Java 8+).
  • Returns a sequential stream for the list, enabling operations like filter(), map(), sorted(), collect(), etc.
  • Promotes declarative and cleaner code for data processing.
  • Does not modify the original list—streams are immutable pipelines of operations.

Use Case: Perform advanced operations like filtering names starting with “A”.

List<String> names = Arrays.asList("Alice", "Bob", "Anna", "Charlie");

names.stream()
     .filter(name -> name.startsWith("A"))
     .forEach(System.out::println); // Output: Alice, Anna

🔍 Explanation:

  • stream() creates a stream from the list.
  • filter() keeps only names that start with "A".
  • forEach() prints each filtered name.

✅ Java 8+ Feature
Perfect for:

  • Filtering data
  • Transforming list items
  • Grouping and aggregating values
  • Working with large data sets efficiently