ArrayList methods is essential for every Java developer. ArrayList
is part of the Java Collections Framework, providing a dynamic, resizable array that comes packed with versatile methods for list operations.
Introduction to ArrayList Methods
The ArrayList
class in Java offers a variety of methods to add, remove, search, sort, and manipulate list elements. These methods make it easy to perform common tasks such as inserting data, finding elements, or clearing the list—all with simple and efficient code.
Java ArrayList Methods with Examples
Method | Description | Example |
---|---|---|
add(E e) | Adds an element at the end of the list. | list.add("Apple"); |
add(int index, E e) | Adds an element at the specified index. | list.add(1, "Orange"); |
addAll(Collection c) | Adds all elements from another collection. | list.addAll(otherList); |
addAll(int index, Collection c) | Inserts all elements from a collection at a specific index. | list.addAll(2, extraList); |
clear() | Removes all elements from the list. | list.clear(); |
clone() | Creates a shallow copy of the list. | ArrayList cloneList = (ArrayList) list.clone(); |
contains(Object o) | Checks if the list contains the specified element. | list.contains("Banana"); |
ensureCapacity(int minCap) | Increases the capacity of the list to at least the specified capacity. | list.ensureCapacity(50); |
forEach(Consumer action) | Performs an action for each element. | list.forEach(e -> System.out.println(e)); |
get(int index) | Returns the element at the specified index. | String item = list.get(0); |
indexOf(Object o) | Returns the first index of the element, or -1 if not found. | int i = list.indexOf("Apple"); |
isEmpty() | Returns true if the list is empty. | list.isEmpty(); |
iterator() | Returns an iterator to loop through the elements. | Iterator it = list.iterator(); |
lastIndexOf(Object o) | Returns the last index of the element. | list.lastIndexOf("Orange"); |
listIterator() | Returns a list iterator over elements. | ListIterator itr = list.listIterator(); |
listIterator(int index) | Returns a list iterator starting at the given index. | ListIterator itr = list.listIterator(2); |
remove(int index) | Removes the element at the specified index. | list.remove(1); |
remove(Object o) | Removes the first occurrence of the specified element. | list.remove("Banana"); |
removeAll(Collection c) | Removes all elements that exist in another collection. | list.removeAll(anotherList); |
removeIf(Predicate filter) | Removes elements that satisfy a given condition. | list.removeIf(name -> name.startsWith("A")); |
replaceAll(UnaryOperator op) | Replaces all elements using a function. | list.replaceAll(e -> e.toUpperCase()); |
retainAll(Collection c) | Retains only elements that exist in the specified collection. | list.retainAll(commonItems); |
set(int index, E e) | Replaces the element at the specified index. | list.set(0, "Grapes"); |
size() | Returns the size — number of elements in list. | int count = list.size(); |
sort(Comparator c) | Sorts the list with the given comparator. | list.sort(Comparator.naturalOrder()); |
spliterator() | Returns a Spliterator for the list. | Spliterator<String> spltr = list.spliterator(); |
subList(int from, int to) | Returns a view of a portion of the list. | List sub = list.subList(1, 3); |
toArray() | Converts the list to a generic Object array. | Object[] arr = list.toArray(); |
toArray(T[] a) | Converts the list to a typed array. | String[] strArr = list.toArray(new String); |
trimToSize() | Shrinks internal capacity to current size. | list.trimToSize(); |
Examples of ArrayList Methods
1. Adding Elements
ArrayList fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add(1, "Orange"); // Inserts at index 1
2. Accessing and Modifying Elements
String first = fruits.get(0); // "Apple"
fruits.set(0, "Mango"); // Now "Mango" at index 0
3. Removing Elements
fruits.remove("Banana"); // Removes first occurrence
fruits.remove(0); // Removes element at index 0
4. Checking Size and Emptiness
int size = fruits.size();
boolean isEmpty = fruits.isEmpty();
5. Searching for Elements
boolean hasOrange = fruits.contains("Orange");
int idx = fruits.indexOf("Orange");
6. Iterating Over Elements
for (String fruit : fruits) {
System.out.println(fruit);
}
7. Converting to Array
String[] fruitsArray = fruits.toArray(new String[0]);
8. Using SubList
// View from index 0 to 1
List<String> subFruits = fruits.subList(0, 2);
Useful Tips
ArrayList
allows duplicate elements and maintains insertion order.- Use generics for type safety:
ArrayList<Integer> numbers = new ArrayList<>();
- For thread-safe operations, consider
Collections.synchronizedList
orCopyOnWriteArrayList
. - Prefer enhanced for-loop or Java Streams for concise iteration and processing.
Example: All Methods Combined
import java.util.*; public class ArrayListDemo { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); System.out.println(list.get(1)); // B list.set(1, "D"); list.remove("A"); list.remove(1); System.out.println(list.contains("D")); // true list.clear(); System.out.println(list.isEmpty()); // true } }
Conclusion
Mastering Java ArrayList methods is crucial for effective data management in Java applications. These methods provide the flexibility and power needed for any dynamic list processing task, making ArrayList
a fundamental tool in every Java developer’s toolkit.