Last Updated: 07 November, 2023
Java ArrayList is a class in the Java Collections Framework that implements the java.util.List interface. It was introduced in the JDK 1.2 version and is available in the java.util package.
An ArrayList is used to store a dynamically sized collection of elements (a resizable array), which means that it can grow and shrink dynamically as needed. Elements can be added, modified, and removed from an ArrayList whenever there is a need.
ArrayList is a good choice for storing groups of elements that need to be accessed and manipulated frequently, as well as for storing collections of elements that are unknown in size at runtime.
As we can see from the complete ArrayList class hierarchy above, the ArrayList class extends the AbstractList class and implements the List, RandomAccess, Cloneable, and Serializable Interfaces.
Here, E defines the type of elements that the List will contain.
Output
ArrayList Elements: [India, Canada, US, England]
Java ArrayList class has the following constructors.
Constructor Name and Descriptions |
---|
ArrayList() Constructs an empty list with an initial capacity of ten. |
ArrayList(Collection<? extends E> c) Constructs a list containing the elements of the specified collection in the order they are returned by the collection's iterator. |
ArrayList(int initialCapacity) Constructs an empty list with the specified initial capacity. |
The Java ArrayList class has the following methods:
Method Name | Description |
---|---|
add(Object o) | This method is used to append a specific element to the end of a list. |
add(int index, Object element) | This method is used to insert a specific element at a specific position index in a list. |
addAll(Collection C) | This method is used to append all the elements from a specific collection to the end of the mentioned list in such an order that the values are returned by the specified collection’s iterator. |
addAll(int index, Collection C) | Used to insert all of the elements starting at the specified position from a specific collection into the mentioned list. |
clear() | This method is used to remove all the elements from any list. |
clone() | This method is used to return a shallow copy of an ArrayList. |
contains(Object o) | Returns true if this list contains the specified element. |
ensureCapacity(int minCapacity) | Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument. |
forEach(Consumer<? super E> action) | Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. |
get(int index) | Returns the element at the specified position in this list. |
indexOf(Object O) | The index for the first occurrence of a specific element is either returned or -1 in case the element is not in the list. |
isEmpty() | Returns true if this list contains no elements. |
lastIndexOf(Object O) | The index of the last occurrence of a specific element is either returned or -1 in case the element is not in the list. |
listIterator() | It returns a list iterator over the elements in this list (in proper sequence). |
listIterator(int index) | Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list. |
remove(int index) | Removes the element at the specified position in this list. |
remove(Object o) | Removes the first occurrence of the specified element from this list, if it is present. |
removeAll(Collection c) | Removes from this list all of its elements that are contained in the specified collection. |
removeIf(Predicate filter) | Removes all of the elements of this collection that satisfy the given predicate. |
removeRange(int fromIndex, int toIndex) | Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive. |
retainAll(Collection<?> c) | Retains only the elements in this list that are contained in the specified collection. |
set(int index, E element) | Replaces the element at the specified position in this list with the specified element. |
size() | Returns the number of elements in this list. |
spliterator() | Creates a late-binding and fail-fast Spliterator over the elements in this list. |
subList(int fromIndex, int toIndex) | Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. |
toArray() | This method is used to return an array containing all of the elements in the list in the correct order. |
toArray(Object[] O) | It is also used to return an array containing all of the elements in this list in the correct order, the same as the previous method. |
trimToSize() | This method is used to trim the capacity of the instance of the ArrayList to the list’s current size. |
The Java ArrayList class provided methods are implemented in the below given examples. Let's go through the examples one by one and understand the uses for each method.
Example 1 : Methods for Adding elements in ArrayList
Output
ArrayList elements: [100, 200, 400, 500]
ArrayList elements after adding elements at index 2 : [100, 200, 300, 400, 500]
ArrayList elements after adding another ArrayList : [100, 200, 300, 600, 700, 400, 500, 600, 700]
ArrayList elements : [A, B, C, D]
Example 2 : Method for Accessing elements from ArrayList
Output
ArrayList value : South Africa
Example 3 : Methods for Updating elements in ArrayList
Output
ArrayList elements: [100, 200, 400, 400]
ArrayList after update the element: [100, 200, 300, 400]
Example 4 : Methods for Removing elements from ArrayList
Output
ArrayList elements: [Java, Hibernate, Kafka, MongoDB, Jenkins, MySQL, JSF, Spring, Microservices]
Array List after calling remove(int index) method: [Java, Hibernate, Kafka, Jenkins, MySQL, JSF, Spring, Microservices]
Array List after calling remove(Object o) method: [Java, Hibernate, Kafka, Jenkins, MySQL, Spring, Microservices]
Array List after calling removeAll(Collection c) method: [Java, Hibernate, Jenkins, Spring]
After all remove() methods, Final ArrayList elements:
Hibernate
Spring
Example 5 : Utility methods of ArrayList
Output
true
false
false
ArrayList Size Before : 5
ArrayList Size After : 0
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/ArrayList.html
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com
How to Convert a Non-Synchronized to Synchronized ArrayList?
Ans. The default implementation of ArrayList is non-synchronized. That means if multiple threads access an ArrayList instance concurrently and at least one of the threads modifies the list structurally, it must be synchronized externally.
Java has provided one utility class for this purpose. Please have a look.
ArrayList Vs Array in Java.
Ans. There are the following differences between ArrayList and Array:
ArrayList | Array |
---|---|
The size of an ArrayList is dynamic and can be increased or decreased as needed. | Array size is fixed. Once declared, its size can’t be changed. |
ArrayList can only have one dimension. | An array can be single or multidimensional. |
ArrayList can only hold reference types (objects), not primitives. | An array can hold both primitives and reference types (objects) in Java. |
ArrayList supports generics. | Array does not support generics. |
When compared to an array, an ArrayList performs worse and consumes more memory. | Array provides better performance and uses less memory. |
ArralyList provides various ways for iteration, like loops, Iterator, and ListIterator class. | We can iterate through an array using loops only. |
ArrayList elements are not stored at contiguous memory locations. | Array elements are stored at contiguous memory locations. |
We can add elements to the ArrayList using the add() method. | Using the assignment operator, we can add elements to the array. |
How to convert an ArrayList to an Array and an Array to an ArrayList in Java?
Ans. ArrayList can be converted into an array using the toArray() method of the ArrayList class.
Syntax: public Object[] toArray()
Example:
List<Integer> list = new ArrayList<Integer>();
list.add(20);
list.add(40);
list.add(60);
list.add(80);
Object[] objects = list.toArray();
An array can be converted into an ArrayList by making use of the asList() method provided by the java.util.Arrays class. It is a static method that accepts List objects as a parameter.
Syntax: Arrays.asList(item)
Example:
char[] values = {'A', 'B', 'C', 'D', 'E'};
ArrayList
Why is ArrayList a better choice than Array?
Ans. The limitation with an array is that it has a fixed length, so once it is full, we cannot add any more elements. Likewise, if a number of elements are removed from it, the memory consumption would be the same as if it didn’t shrink.
An ArrayList, on the other hand, can grow and shrink dynamically as elements are added and removed. Also, ArrayList provides many predefined methods, which makes the developer's job easier.
What is the major difference between an ArrayList and a Vector in Java?
ArrayList and Vector both implement the List Interface and maintain data insertion order, and both classes have a default capacity of 10, but apart from these similarities, both classes have so many major differences. Let's take a look at the table below.
Comparison Parameters | ArrayList Vs Vector |
Synchronization | ArrayList is not synchronized (not thread-safe), which means multiple threads can access an ArrayList object at the same time. Vector, on the other hand, is synchronised (thread-safe), so only one thread can access the vector object at a time. |
Performance | ArrayList is faster since it is non-synchronized, whereas Vector is by default synchronized so its operations give slower performance. |
Data Growth | ArrayList and Vector both grow and shrink dynamically to maintain optimal use of storage. ArrayList increases by 50% of the current array size if the number of elements exceeds its capacity, whereas Vector increases by 100%, essentially doubling the current array size. |
Traversal | ArrayList can only use an iterator to traverse its elements, whereas Vector can use both an enumeration and an iterator to traverse its elements. |
Legacy Class | ArrayList was introduced in the JDK 1.2 version, and ArrayList is not a legacy class, whereas Vector is a legacy class. It was introduced in the JDK 1.0 version. |
What is the difference between an ArrayList’s clear() and removeAll() methods?
Ans. Both methods look similar, but they perform differently.
The clear () method deletes all of the elements from an ArrayList, leaving it empty.
The removeAll() method takes a collection as a parameter and removes all of the ArrayList elements that are part of the collection.
Syntax:
public void clear();
public boolean removeAll(Collection c);
How to remove duplicate elements from an ArrayList in Java?
Ans. It's very simple; let's understand it with the help of the given example.
List
list.add(20);
list.add(30);
list.add(20);
Set
What is the difference between an ArrayList and a LinkedList?
Ans. Both have the following differences:
ArrayList | LinkedList |
---|---|
ArrayList internally uses a dynamic array to store the elements. | LinkedList internally uses a doubly linked list to store the elements. |
ArrayList implements the List interface. Therefore, this acts as a list. | LinkedList implements both the List interface and the Deque interface. Therefore, it can act as both a list and a deque. |
ArrayList is slow because array manipulation is slower. | LinkedList is faster than node-based as there is not much bit shifting required. |
ArrayList is best for storing and accessing elements from the list. | For manipulating the elements, LinkedList is the best choice. |
ArrayList allocates contiguous memory locations. | LinkedList does not allocate contiguous memory locations. |
The default capacity of an ArrayList is 10. | LinkedList has no default capacity. An empty list is created when a LinkedList is initialized. |