Java ArrayList Class
The ArrayList class is a part of java collection framework. It is available inside the java.util package. The ArrayList class extends AbstractList class and implements List interface.
The elements of ArrayList are organized as an array internally. The default size of an ArrayList is 10.
The ArrayList class is used to create a dynamic array that can grow or shrunk as needed.
🔔 The ArrayList is a child class of AbstractList
🔔 The ArrayList implements interfaces like List, Serializable, Cloneable, and RandomAccess.
🔔 The ArrayList allows to store duplicate data values.
🔔 The ArrayList allows to access elements randomly using index-based accessing.
🔔 The ArrayList maintains the order of insertion.
ArrayList class declaration
The ArrayList class has the following declaration.
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable
ArrayList class constructors
The ArrayList class has the following constructors.
- ArrayList( ) - Creates an empty ArrayList.
- ArrayList(Collection c) - Creates an ArrayList with given collection of elements.
- ArrayList(int size) - Creates an empty ArrayList with given size (capacity).
Operations on ArrayList
The ArrayList class allow us to perform several operations like adding, accesing, deleting, updating, looping, etc. Let's look at each operation with examples.
Adding Items
The ArrayList class has the following methods to add items.
- boolean add(E element) - Appends given element to the ArrayList.
- boolean addAll(Collection c) - Appends given collection of elements to the ArrayList.
- void add(int index, E element) - Inserts the given element at specified index.
- boolean addAll(int index, Collection c) - Inserts the given collection of elements at specified index.
Let's consider an example program to illustrate adding items to the ArrayList.
import java.util.*;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> list_1 = new ArrayList<String>();
ArrayList list_2 = new ArrayList();
//Appending
list_1.add("BTech");
System.out.println("list_1: " + list_1);
list_1.add("Class");
System.out.println("list_1: " + list_1);
//Inserting at specified index
list_1.add(1, "Smart");
System.out.println("list_1: " + list_1);
//Appending a collection of elements
list_2.addAll(list_1);
System.out.println("list_2: " + list_2);
//Inserting collection of elements at specified index
list_2.addAll(2, list_1);
System.out.println("list_2: " + list_2);
}
}
Accessing Items
The ArrayList class has the following methods to access items.
- E get(int index) - Returns element at specified index from the ArrayList.
- ArrayList subList(int startIndex, int lastIndex) - Returns an ArrayList that contails elements from specified startIndex to lastIndex-1 from the invoking ArrayList.
- int indexOf(E element) - Returns the index value of given element first occurence in the ArrayList.
- int lastIndexOf(E element) - Returns the index value of given element last occurence in the ArrayList.
Let's consider an example program to illustrate accessing items from the ArrayList.
import java.util.*;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> list_1 = new ArrayList<String>();
list_1.add("BTech");
list_1.add("Smart");
list_1.add("Class");
list_1.add("-");
list_1.add("Java");
list_1.add("Tutorial");
list_1.add("Class");
System.out.println("Element at index 4 is " + list_1.get(4));
System.out.println("Sublist from index 1 to 4: " + list_1.subList(1, 5));
System.out.println("Index of element \"Class\" is " + list_1.indexOf("Class"));
System.out.println("Last index of element \"Class\" is " + list_1.lastIndexOf("Class"));
}
}
Updating Items
The ArrayList class has the following methods to update or change items.
- E set(int index, E newElement) - Replace the element at specified index with newElement in the invoking ArrayList.
- ArrayList replaceAll(UnaryOperator e) - Replaces each element of invoking ArrayList with the result of applying the operator to that element.
Let's consider an example program to illustrate updating items in the ArrayList.
import java.util.*;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> list_1 = new ArrayList<String>();
list_1.add("BTech");
list_1.add("Smart");
list_1.add("Class");
list_1.add("-");
list_1.add("Java");
list_1.add("Tutorial");
list_1.add("Class");
System.out.println("\nList before update: " + list_1);
list_1.set(3, ":");
System.out.println("\nList after update: " + list_1);
list_1.replaceAll(e -> e.toUpperCase());
System.out.println("\nList after update: " + list_1);
}
}
Removing Items
The ArrayList class has the following methods to remove items.
- E remove(int index) - Removes the element at specified index in the invoking ArrayList.
- boolean remove(Object element) - Removes the first occurence of the given element from the invoking ArrayList.
- boolean removeAll(Collection c) - Removes the given collection of elements from the invoking ArrayList.
- void retainAll(Collection c) - Removes all the elements except the given collection of elements from the invoking ArrayList.
- boolean removeIf(Predicate filter) - Removes all the elements from the ArrayList that satisfies the given predicate.
- void clear( ) - Removes all the elements from the ArrayList.
Let's consider an example program to illustrate removing items from the ArrayList.
import java.util.*;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> list_1 = new ArrayList<String>();
ArrayList list_2 = new ArrayList();
ArrayList list_3 = new ArrayList();
list_1.add("BTech");
list_1.add("Smart");
list_1.add("Class");
list_1.add("-");
list_1.add("Java");
list_1.add("Tutorial");
list_1.add("Classes");
list_1.add("on");
list_1.add("Collection");
list_1.add("framwork");
list_1.add("-");
list_1.add("ArrayList");
list_2.add("Tutorial");
list_2.add("Java");
list_3.add("BTech");
list_3.add("Smart");
list_3.add("Class");
System.out.println("\nList_1 before remove:\n" + list_1);
System.out.println("\nList_2 before remove:\n" + list_2);
System.out.println("\nList_3 before remove:\n" + list_3);
list_1.remove(3);
System.out.println("\nList after removing element from index 3:\n" + list_1);
list_1.remove("Tutorial");
System.out.println("\nList after removing \'Tutorial\' element:\n" + list_1);
list_1.removeAll(list_2);
System.out.println("\nList after removing all elements of list_2 from list_1:\n" + list_1);
list_1.removeIf(n -> n.equals("Classes"));
System.out.println("\nList after removing all elements that are equal to \'Classes\':\n" + list_1);
list_1.retainAll(list_3);
System.out.println("\nList after removing all elements from list_1 except elements of list_3:\n" + list_1);
list_1.clear();
System.out.println("\nList after removing all elements from list_1:\n" + list_1);
}
}
Other utility methods
The ArrayList class has the following methods to work with elements of it.
- int size( ) - Returns the total number of elements in the invoking ArrayList.
- boolean isEmpty( ) - Returns true if the list is empty otherwise returns false.
- boolean contains(Object element) - Returns true if the list contains given element otherwise returns false.
- void sort(Comparator c) - Sorts all the elements of invoking list based on the given comparator.
- List[ ] subList(int startIndex, int endIndex) - Returns list of elements starting from startIndex to endIndex-1.
- Object clone( ) - Returns a shallow copy of an ArrayList.
- Object[ ] toArray( ) - Returns an array of Object instances that contains all the elements from invoking ArrayList.
- Spliterator spliterator( ) - Creates spliterator over the elements in a list.
- void trimToSize( ) - Used to trim a ArrayList instance to the number of elements it contains.
Let's consider an example program to illustrate other utility methods of the ArrayList.
import java.util.*;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList list = new ArrayList(20);
Random number = new Random();
for(int i = 1; i<=10; i++)
list.add(number.nextInt(100));
System.out.println("\nList before remove:\n" + list);
System.out.println("\nList size: " + list.size());
System.out.println("\nList empty status: " + list.isEmpty());
System.out.println("\nList contains 10: " + list.contains(10));
System.out.println("\nSublist from index 2 to 6: " + list.subList(2, 7) + "\n");
Spliterator nums = list.spliterator();
nums.forEachRemaining((n) -> System.out.print(n + ", "));
Object[] objs = list.toArray();
System.out.println("\n");
for(Object obj:objs)
System.out.print(obj + ", ");
Object anotherList = new ArrayList();
anotherList = list.clone();
System.out.println("\n\nClonned object elements:\n" + anotherList);
list.sort(null); // from ArrayList class
Collections.sort(list); // from Collections class
System.out.println("\n\nList_1 in sorted order:\n" + list);
list.trimToSize();
}
}
Consolidated list of methods
The following table providess a consolidated view of all methods of ArrayList.
Method | Description |
---|---|
boolean add(E element) | Appends given element to the ArrayList. |
boolean addAll(Collection c) | Appends given collection of elements to the ArrayList. |
void add(int index, E element) | Inserts the given element at specified index. |
boolean addAll(int index, Collection c) | Inserts the given collection of elements at specified index. |
E get(int index) | Returns element at specified index from the ArrayList. |
ArrayList subList(int startIndex, int lastIndex) | Returns an ArrayList that contails elements from specified startIndex to lastIndex-1 from the invoking ArrayList. |
int indexOf(E element) | Returns the index value of given element first occurence in the ArrayList. |
int lastIndexOf(E element) | Returns the index value of given element last occurence in the ArrayList. |
E set(int index, E newElement) | Replace the element at specified index with newElement in the invoking ArrayList. |
ArrayList replaceAll(UnaryOperator e) | Replaces each element of invoking ArrayList with the result of applying the operator to that element. |
E remove(int index) | Removes the element at specified index in the invoking ArrayList. |
boolean remove(Object element) | Removes the first occurence of the given element from the invoking ArrayList. |
boolean removeAll(Collection c) | Removes the given collection of elements from the invoking ArrayList. |
void retainAll(Collection c) | Removes all the elements except the given collection of elements from the invoking ArrayList. |
boolean removeIf(Predicate filter) | Removes all the elements from the ArrayList that satisfies the given predicate. |
void clear( ) | Removes all the elements from the ArrayList. |
int size( ) | Returns the total number of elements in the invoking ArrayList. |
boolean isEmpty( ) | Returns true if the list is empty otherwise returns false. |
boolean contains(Object element) | Returns true if the list contains given element otherwise returns false. |
void sort(Comparator c) | Sorts all the elements of invoking list based on the given comparator. |
List[ ] subList(int startIndex, int endIndex) | Returns list of elements starting from startIndex to endIndex-1. |
Object clone( ) | Returns a shallow copy of an ArrayList. |
Object[ ] toArray( ) | Returns an array of Object instances that contains all the elements from invoking ArrayList. |
Spliterator spliterator( ) | Creates spliterator over the elements in a list. |
void trimToSize( ) | Used to trim a ArrayList instance to the number of elements it contains. |