Java ArrayList Class Tutorial

This tutorial will cover all the essential methods of the ArrayList class in Java, explaining how each method works and providing examples to demonstrate their usage.

Table of Contents

  1. Introduction
  2. ArrayList Basics
  3. ArrayList Methods
    • add(E e)
    • add(int index, E element)
    • addAll(Collection<? extends E> c)
    • addAll(int index, Collection<? extends E> c)
    • clear()
    • clone()
    • contains(Object o)
    • ensureCapacity(int minCapacity)
    • equals(Object o)
    • forEach(Consumer<? super E> action)
    • get(int index)
    • indexOf(Object o)
    • isEmpty()
    • iterator()
    • lastIndexOf(Object o)
    • listIterator()
    • listIterator(int index)
    • remove(int index)
    • remove(Object o)
    • removeAll(Collection<?> c)
    • removeIf(Predicate<? super E> filter)
    • retainAll(Collection<?> c)
    • set(int index, E element)
    • size()
    • spliterator()
    • subList(int fromIndex, int toIndex)
    • toArray()
    • toArray(T[] a)
    • trimToSize()
  4. Conclusion

Introduction

The ArrayList class in Java is part of the java.util package and provides a resizable array implementation. It allows for dynamic arrays that can grow as needed, making it a versatile and commonly used data structure.

ArrayList Basics

Before diving into the methods, let’s create a basic ArrayList and understand its usage.

Example

import java.util.ArrayList; public class ArrayListBasics { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add("Orange"); System.out.println("ArrayList: " + list); } } 

Output:

ArrayList: [Apple, Banana, Orange] 

ArrayList Methods

add(E e)

Adds an element to the end of the ArrayList.

Example

import java.util.ArrayList; public class AddExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); System.out.println("ArrayList: " + list); } } 

Output:

ArrayList: [Apple, Banana] 

add(int index, E element)

Inserts an element at the specified position in the ArrayList.

Example

import java.util.ArrayList; public class AddAtIndexExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add(1, "Orange"); System.out.println("ArrayList: " + list); } } 

Output:

ArrayList: [Apple, Orange, Banana] 

addAll(Collection<? extends E> c)

Adds all elements from the specified collection to the end of the ArrayList.

Example

import java.util.ArrayList; import java.util.Arrays; public class AddAllExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.addAll(Arrays.asList("Banana", "Orange")); System.out.println("ArrayList: " + list); } } 

Output:

ArrayList: [Apple, Banana, Orange] 

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

Inserts all elements from the specified collection at the specified position in the ArrayList.

Example

import java.util.ArrayList; import java.util.Arrays; public class AddAllAtIndexExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.addAll(1, Arrays.asList("Orange", "Grapes")); System.out.println("ArrayList: " + list); } } 

Output:

ArrayList: [Apple, Orange, Grapes, Banana] 

clear()

Removes all elements from the ArrayList.

Example

import java.util.ArrayList; public class ClearExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.clear(); System.out.println("ArrayList: " + list); } } 

Output:

ArrayList: [] 

clone()

Returns a shallow copy of the ArrayList.

Example

import java.util.ArrayList; public class CloneExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); ArrayList<String> clonedList = (ArrayList<String>) list.clone(); System.out.println("Cloned ArrayList: " + clonedList); } } 

Output:

Cloned ArrayList: [Apple, Banana] 

contains(Object o)

Returns true if the ArrayList contains the specified element.

Example

import java.util.ArrayList; public class ContainsExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); boolean containsApple = list.contains("Apple"); boolean containsGrapes = list.contains("Grapes"); System.out.println("Contains Apple: " + containsApple); System.out.println("Contains Grapes: " + containsGrapes); } } 

Output:

Contains Apple: true Contains Grapes: false 

ensureCapacity(int minCapacity)

Increases the capacity of the ArrayList to ensure it can hold at least the number of elements specified by the minimum capacity argument.

Example

import java.util.ArrayList; public class EnsureCapacityExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(2); list.add("Apple"); list.add("Banana"); list.ensureCapacity(10); list.add("Orange"); list.add("Grapes"); System.out.println("ArrayList: " + list); } } 

Output:

ArrayList: [Apple, Banana, Orange, Grapes] 

equals(Object o)

Compares the specified object with this list for equality.

Example

import java.util.ArrayList; public class EqualsExample { public static void main(String[] args) { ArrayList<String> list1 = new ArrayList<>(); list1.add("Apple"); list1.add("Banana"); ArrayList<String> list2 = new ArrayList<>(); list2.add("Apple"); list2.add("Banana"); boolean isEqual = list1.equals(list2); System.out.println("Lists are equal: " + isEqual); } } 

Output:

Lists are equal: true 

forEach(Consumer<? super E> action)

Performs the given action for each element of the ArrayList.

Example

import java.util.ArrayList; public class ForEachExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add("Orange"); list.forEach(element -> System.out.println(element)); } } 

Output:

Apple Banana Orange 

get(int index)

Returns the element at the specified position in the ArrayList.

Example

import java.util.ArrayList; public class GetExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); String element = list.get(1); System.out.println("Element at index 1: " + element); } } 

Output:

Element at index 1: Banana 

indexOf(Object o)

Returns the index of the first occurrence of the specified element in the ArrayList, or -1 if the ArrayList does not contain the element.

Example

import java.util.ArrayList; public class IndexOfExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); int index = list.indexOf("Banana"); System.out.println("Index of Banana: " + index); } } 

Output:

Index of Banana: 1 

isEmpty()

Returns true if the ArrayList contains no elements.

Example

import java.util.ArrayList; public class IsEmptyExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); boolean isEmpty = list.isEmpty(); System.out.println("Is the ArrayList empty? " + isEmpty); list.add("Apple"); isEmpty = list.isEmpty(); System.out.println("Is the ArrayList empty? " + isEmpty); } } 

Output:

Is the ArrayList empty? true Is the ArrayList empty? false 

iterator()

Returns an iterator over the elements in the ArrayList in proper sequence.

Example

import java.util.ArrayList; import java.util.Iterator; public class IteratorExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add("Orange"); Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } } 

Output:

Apple Banana Orange 

lastIndexOf(Object o)

Returns the index of the last occurrence of the specified element in the ArrayList, or -1 if the ArrayList does not contain the element.

Example

import java.util.ArrayList; public class LastIndexOfExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add("Apple"); int lastIndex = list.lastIndexOf("Apple"); System.out.println("Last index of Apple: " + lastIndex); } } 

Output:

Last index of Apple: 2 

listIterator()

Returns a list iterator over the elements in the ArrayList in proper sequence.

Example

import java.util.ArrayList; import java.util.ListIterator; public class ListIteratorExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add("Orange"); ListIterator<String> listIterator = list.listIterator(); while (listIterator.hasNext()) { System.out.println(listIterator.next()); } } } 

Output:

Apple Banana Orange 

listIterator(int index)

Returns a list iterator over the elements in the ArrayList, starting at the specified position in the list.

Example

import java.util.ArrayList; import java.util.ListIterator; public class ListIteratorFromIndexExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add("Orange"); ListIterator<String> listIterator = list.listIterator(1); while (listIterator.hasNext()) { System.out.println(listIterator.next()); } } } 

Output:

Banana Orange 

remove(int index)

Removes the element at the specified position in the ArrayList.

Example

import java.util.ArrayList; public class RemoveAtIndexExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add("Orange"); String removedElement = list.remove(1); System.out.println("Removed element: " + removedElement); System.out.println("ArrayList after removal: " + list); } } 

Output:

Removed element: Banana ArrayList after removal: [Apple, Orange] 

remove(Object o)

Removes the first occurrence of the specified element from the ArrayList, if it is present.

Example

import java.util.ArrayList; public class RemoveObjectExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add("Orange"); boolean isRemoved = list.remove("Banana"); System.out.println("Was Banana removed? " + isRemoved); System.out.println("ArrayList after removal: " + list); } } 

Output:

Was Banana removed? true ArrayList after removal: [Apple, Orange] 

removeAll(Collection<?> c)

Removes from the ArrayList all of its elements that are contained in the specified collection.

Example

import java.util.ArrayList; import java.util.Arrays; public class RemoveAllExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(Arrays.asList("Apple", "Banana", "Orange", "Grapes")); ArrayList<String> elementsToRemove = new ArrayList<>(Arrays.asList("Banana", "Grapes")); boolean isRemoved = list.removeAll(elementsToRemove); System.out.println("Were elements removed? " + isRemoved); System.out.println("ArrayList after removal: " + list); } } 

Output:

Were elements removed? true ArrayList after removal: [Apple, Orange] 

removeIf(Predicate<? super E> filter)

Removes all of the elements of this collection that satisfy the given predicate.

Example

import java.util.ArrayList; public class RemoveIfExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add("Orange"); boolean isRemoved = list.removeIf(element -> element.startsWith("B")); System.out.println("Were elements removed? " + isRemoved); System.out.println("ArrayList after removal: " + list); } } 

Output:

Were elements removed? true ArrayList after removal: [Apple, Orange] 

retainAll(Collection<?> c)

Retains only the elements in the ArrayList that are contained in the specified collection.

Example

import java.util.ArrayList; import java.util.Arrays; public class RetainAllExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(Arrays.asList("Apple", "Banana", "Orange", "Grapes")); ArrayList<String> elementsToRetain = new ArrayList<>(Arrays.asList("Banana", "Grapes")); boolean isRetained = list.retainAll(elementsToRetain); System.out.println("Were elements retained? " + isRetained); System.out.println("ArrayList after retainAll: " + list); } } 

Output:

Were elements retained? true ArrayList after retainAll: [Banana, Grapes] 

set(int index, E element)

Replaces the element at the specified position in the ArrayList with the specified element.

Example

import java.util.ArrayList; public class SetExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add("Orange"); String replacedElement = list.set(1, "Grapes"); System.out.println("Replaced element: " + replacedElement); System.out.println("ArrayList after set: " + list); } } 

Output:

Replaced element: Banana ArrayList after set: [Apple, Grapes, Orange] 

size()

Returns the number of elements in the ArrayList.

Example

import java.util.ArrayList; public class SizeExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); int size = list.size(); System.out.println("Size of ArrayList: " + size); } } 

Output:

Size of ArrayList: 2 

spliterator()

Creates a Spliterator over the elements in the ArrayList.

Example

import java.util.ArrayList; import java.util.Spliterator; public class SpliteratorExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add("Orange"); Spliterator<String> spliterator = list.spliterator(); spliterator.forEachRemaining(System.out::println); } } 

Output:

Apple Banana Orange 

subList(int fromIndex, int toIndex)

Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.

Example

import java.util.ArrayList; import java.util.List; public class SubListExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Apple "); list.add("Banana"); list.add("Orange"); list.add("Grapes"); List<String> subList = list.subList(1, 3); System.out.println("SubList: " + subList); } } 

Output:

SubList: [Banana, Orange] 

toArray()

Returns an array containing all of the elements in this list in proper sequence (from first to last element).

Example

import java.util.ArrayList; public class ToArrayExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add("Orange"); Object[] array = list.toArray(); System.out.println("Array elements:"); for (Object element : array) { System.out.println(element); } } } 

Output:

Array elements: Apple Banana Orange 

toArray(T[] a)

Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.

Example

import java.util.ArrayList; public class ToTypedArrayExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add("Orange"); String[] array = list.toArray(new String[0]); System.out.println("Array elements:"); for (String element : array) { System.out.println(element); } } } 

Output:

Array elements: Apple Banana Orange 

trimToSize()

Trims the capacity of this ArrayList instance to be the list’s current size.

Example

import java.util.ArrayList; public class TrimToSizeExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(10); list.add("Apple"); list.add("Banana"); list.add("Orange"); System.out.println("ArrayList before trimToSize: " + list); list.trimToSize(); System.out.println("ArrayList after trimToSize: " + list); } } 

Output:

ArrayList before trimToSize: [Apple, Banana, Orange] ArrayList after trimToSize: [Apple, Banana, Orange] 

Conclusion

This tutorial has covered all the essential methods of the ArrayList class in Java with detailed explanations and examples. By understanding these methods, you can effectively use ArrayList to manage collections of data in your Java applications. Whether you need to add, remove, iterate, or manipulate elements, the ArrayList class provides a versatile and powerful toolset for handling dynamic arrays.

Leave a Comment

Scroll to Top