This tutorial will give you a brief insight about ArrayList in Java and its various constructors and methods along with an example. Unlock the power of Java ArrayList! Dive into this comprehensive guide covering everything you need to know about ArrayList in Java.
Java ArrayList is a part of the Java collection framework and it is a class of java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. This class is found in java.util package. The main advantage of Java ArrayList is, if we declare an array then we need to mention the size, but in ArrayList, it is not needed to mention the size of ArrayList. If you want to mention the size then you can do it.
ArrayList is a Java class implemented using the List interface. Java ArrayList, as the name suggests, provides the functionality of a dynamic array where the size is not fixed as an array. Also, as a part of the Collection framework, it has many features not available with arrays.
Example 1: The following implementation demonstrates how to create and use an ArrayList with a mention of its size.
// Java program to demonstrate the
// working of ArrayList
import java.io.*;
import java.util.*;
class ArrayListExample {
public static void main(String[] args)
{
// Size of the
// ArrayList
int n = 5;
// Declaring the ArrayList with
// initial size n
ArrayList<Integer> arr1 = new ArrayList<Integer>(n);
// Declaring the ArrayList
ArrayList<Integer> arr2 = new ArrayList<Integer>();
// Printing the ArrayList
System.out.println("Array 1:" + arr1);
System.out.println("Array 2:" + arr2);
// Appending new elements at
// the end of the list
for (int i = 1; i <= n; i++) {
arr1.add(i);
arr2.add(i);
}
// Printing the ArrayList
System.out.println("Array 1:" + arr1);
System.out.println("Array 2:" + arr2);
}
}
OutputArray 1:[] Array 2:[] Array 1:[1, 2, 3, 4, 5] Array 2:[1, 2, 3, 4, 5]
ArrayList is a dynamic array and we do not have to specify the size while creating it, the size of the array automatically increases when we dynamically add and remove items. Though the actual library implementation may be more complex, the following is a very basic idea explaining the working of the array when the array becomes full and if we try to add an item:
Let’s understand the Java ArrayList in depth. Look at the below image:
In the above illustration, AbstractList, CopyOnWriteArrayList, and AbstractSequentialList are the classes that implement the list interface. A separate functionality is implemented in each of the mentioned classes. They are:
In order to create an ArrayList, we need to create an object of the ArrayList class. The ArrayList class consists of various constructors which allow the possible creation of the array list. The following are the constructors available in this class:
This constructor is used to build an empty array list. If we wish to create an empty ArrayList with the name arr, then, it can be created as:
ArrayList arr = new ArrayList();
This constructor is used to build an array list initialized with the elements from the collection c. Suppose, we wish to create an ArrayList arr which contains the elements present in the collection c, then, it can be created as:
ArrayList arr = new ArrayList(c);
This constructor is used to build an array list with the initial capacity being specified. Suppose we wish to create an ArrayList with the initial size being N, then, it can be created as:
ArrayList arr = new ArrayList(N);
Method | Description |
---|---|
add(int index, Object element) | This method is used to insert a specific element at a specific position index in a list. |
add(Object o) | This method is used to append a specific element to the end of 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 in Java. |
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 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?() | 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 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. |
Note: You can also create a generic ArrayList:
// Creating generic integer ArrayList
ArrayList<Integer> arrli = new ArrayList<Integer>();
Let’s see how to perform some basic operations on the ArrayList as listed which we are going to discuss further alongside implementing every operation.
In order to add an element to an ArrayList, we can use the add() method. This method is overloaded to perform multiple operations based on different parameters. They are as follows:
Below is the implementation of the above approach:
// Java Program to Add elements to An ArrayList
// Importing all utility classes
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an Array of string type
ArrayList<String> al = new ArrayList<>();
// Adding elements to ArrayList
// Custom inputs
al.add("Codequs");
al.add("Codequs");
// Here we are mentioning the index
// at which it is to be added
al.add(1, "For");
// Printing all the elements in an ArrayList
System.out.println(al);
}
}
Output
[Codequs, For, Codequs]
After adding the elements, if we wish to change the element, it can be done using the set() method. Since an ArrayList is indexed, the element which we wish to change is referenced by the index of the element. Therefore, this method takes an index and the updated element which needs to be inserted at that index.
Below is the implementation of the above approach:
// Java Program to Change elements in ArrayList
// Importing all utility classes
import java.util.*;
// main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an Arraylist object of string type
ArrayList<String> al = new ArrayList<>();
// Adding elements to Arraylist
// Custom input elements
al.add("Codequs");
al.add("Codequs");
// Adding specifying the index to be added
al.add(1, "Codequs");
// Printing the Arraylist elements
System.out.println("Initial ArrayList " + al);
// Setting element at 1st index
al.set(1, "For");
// Printing the updated Arraylist
System.out.println("Updated ArrayList " + al);
}
}
Output
Initial ArrayList [Codequs, Codequs, v]
Updated ArrayList [Codequs, For, Codequs]
In order to remove an element from an ArrayList, we can use the remove() method. This method is overloaded to perform multiple operations based on different parameters. They are as follows:
Example:
// Java program to Remove Elements in ArrayList
// Importing all utility classes
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an object of arraylist class
ArrayList<String> al = new ArrayList<>();
// Adding elements to ArrayList
// Custom addition
al.add("Codequs");
al.add("Codequs");
// Adding element at specific index
al.add(1, "For");
// Printing all elements of ArrayList
System.out.println("Initial ArrayList " + al);
// Removing element from above ArrayList
al.remove(1);
// Printing the updated Arraylist elements
System.out.println("After the Index Removal " + al);
// Removing this word element in ArrayList
al.remove("Codequs");
// Now printing updated ArrayList
System.out.println("After the Object Removal "
+ al);
}
}
Output
Initial ArrayList [Codequs, For, Codequs]
After the Index Removal [Codequs, Codequs]
After the Object Removal [Codequs]
There are multiple ways to iterate through the ArrayList. The most famous ways are by using the basic for loop in combination with a get() method to get the element at a specific index and the advanced for a loop.
Example
// Java program to Iterate the elements
// in an ArrayList
// Importing all utility classes
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an Arraylist of string type
ArrayList<String> al = new ArrayList<>();
// Adding elements to ArrayList
// using standard add() method
al.add("Codequs");
al.add("Codequs");
al.add(1, "For");
// Using the Get method and the
// for loop
for (int i = 0; i < al.size(); i++) {
System.out.print(al.get(i) + " ");
}
System.out.println();
// Using the for each loop
for (String str : al)
System.out.print(str + " ");
}
}
Output
Codequs For Codequs
Codequs For Codequs
// Java program to get the elemens in ArrayList
import java.io.*;
import java.util.*;
class GFG {
public static void main (String[] args) {
ArrayList<Integer> list = new ArrayList();
// add the number
list.add(9);
list.add(5);
list.add(6);
System.out.println(list);
// get method
Integer n= list.get(1);
System.out.println("at indext 1 number is:"+n);
}
}
Output
[9, 5, 6]
at indext 1 number is:5
// Java program to add the elements
// between two numbers in ArrayList
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
ArrayList<Integer> list = new ArrayList();
list.add(1);
list.add(2);
list.add(4);
System.out.println(list);
// insert missing element 3
list.add(2, 3);
System.out.println(list);
}
}
Output
[1, 2, 4]
[1, 2, 3, 4]
// Java Program for ArrayList Sorting
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
ArrayList<Integer> list = new ArrayList();
list.add(2);
list.add(4);
list.add(3);
list.add(1);
System.out.println("Before sorting list:");
System.out.println(list);
Collections.sort(list);
System.out.println("after sorting list:");
System.out.println(list);
}
}
Output
Before sorting list:
[2, 4, 3, 1]
after sorting list:
[1, 2, 3, 4]
// Java program to find the size
// of elements of an ArrayList
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
ArrayList<Integer> list = new ArrayList();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
int b = list.size();
System.out.println("The size is :" + b);
}
}
Output
The size is :4
Operation | Time Complexity | Space Complexity |
---|---|---|
Inserting Element in ArrayList | O(1) | O(N) |
Removing Element from ArrayList | O(N) | O(1) |
Traversing Elements in ArrayList | O(N) | O(N) |
Replacing Elements in ArrayList | O(1) | O(1) |
ArrayList in Java is a class in the Java Collection framework that implements the List interface. Here are the advantages and disadvantages of using ArrayList in Java.
Points to be remembered from this article are mentioned below:
In Java, we use the ArrayList
class to implement the functionality of resizable-arrays.
It implements the List interface of the collections framework.
In Java, we need to declare the size of an array before we can use it. Once the size of an array is declared, it's hard to change it.
To handle this issue, we can use the ArrayList
class. It allows us to create resizable arrays.
Unlike arrays, arraylists can automatically adjust their capacity when we add or remove elements from them. Hence, arraylists are also known as dynamic arrays.
Before using ArrayList
, we need to import the java.util.ArrayList
package first. Here is how we can create arraylists in Java:
ArrayList<Type> arrayList= new ArrayList<>();
Here, Type indicates the type of an arraylist. For example,
// create Integer type arraylist
ArrayList<Integer> arrayList = new ArrayList<>();
// create String type arraylist
ArrayList<String> arrayList = new ArrayList<>();
In the above program, we have used Integer
not int. It is because we cannot use primitive types while creating an arraylist. Instead, we have to use the corresponding wrapper classes.
Here, Integer
is the corresponding wrapper class of int
.
import java.util.ArrayList;
class Main {
public static void main(String[] args){
// create ArrayList
ArrayList<String> languages = new ArrayList<>();
// Add elements to ArrayList
languages.add("Java");
languages.add("Python");
languages.add("Swift");
System.out.println("ArrayList: " + languages);
}
}
Output
ArrayList: [Java, Python, Swift]
In the above example, we have created an ArrayList
named languages.
Here, we have used the add()
method to add elements to the arraylist. We will learn more about the add()
method later in this tutorial.
The ArrayList
class provides various methods to perform different operations on arraylists. We will look at some commonly used arraylist operations in this tutorial:
To add a single element to the arraylist, we use the add()
method of the ArrayList
class. For example,
import java.util.ArrayList;
class Main {
public static void main(String[] args){
// create ArrayList
ArrayList<String> languages = new ArrayList<>();
// add() method without the index parameter
languages.add("Java");
languages.add("C");
languages.add("Python");
System.out.println("ArrayList: " + languages);
}
}
Output
ArrayList: [Java, C, Python]
In the above example, we have created an ArrayList
named languages. Here, we have used the add()
method to add elements to languages.
To access an element from the arraylist, we use the get()
method of the ArrayList
class. For example,
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> animals = new ArrayList<>();
// add elements in the arraylist
animals.add("Cat");
animals.add("Dog");
animals.add("Cow");
System.out.println("ArrayList: " + animals);
// get the element from the arraylist
String str = animals.get(1);
System.out.print("Element at index 1: " + str);
}
}
Output
ArrayList: [Cat, Dog, Cow]
Element at index 1: Dog
In the above example, we have used the get()
method with parameter 1. Here, the method returns the element at index 1.
To change elements of the arraylist, we use the set()
method of the ArrayList
class. For example,
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> languages = new ArrayList<>();
// add elements in the array list
languages.add("Java");
languages.add("Kotlin");
languages.add("C++");
System.out.println("ArrayList: " + languages);
// change the element of the array list
languages.set(2, "JavaScript");
System.out.println("Modified ArrayList: " + languages);
}
}
Output
ArrayList: [Java, Kotlin, C++] Modified ArrayList: [Java, Kotlin, JavaScript]
In the above example, we have created an ArrayList
named languages. Notice the line,
language.set(2, "JavaScript");
Here, the set()
method changes the element at index 2 to JavaScript.
To remove an element from the arraylist, we can use the remove()
method of the ArrayList
class. For example,
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> animals = new ArrayList<>();
// add elements in the array list
animals.add("Dog");
animals.add("Cat");
animals.add("Horse");
System.out.println("ArrayList: " + animals);
// remove element from index 2
String str = animals.remove(2);
System.out.println("Updated ArrayList: " + animals);
System.out.println("Removed Element: " + str);
}
}
Output
ArrayList: [Dog, Cat, Horse]
Updated ArrayList: [Dog, Cat]
Removed Element: Horse
Here, the remove()
method takes the index number as the parameter. And, removes the element specified by the index number.
In the previous section, we have learned about the add()
, get()
, set()
, and remove()
method of the ArrayList
class.
Besides those basic methods, here are some more ArrayList
methods that are commonly used.
Methods | Descriptions |
---|---|
size() | Returns the length of the arraylist. |
sort() | Sort the arraylist elements. |
clone() | Creates a new arraylist with the same element, size, and capacity. |
contains() | Searches the arraylist for the specified element and returns a boolean result. |
ensureCapacity() | Specifies the total element the arraylist can contain. |
isEmpty() | Checks if the arraylist is empty. |
indexOf() | Searches a specified element in an arraylist and returns the index of the element. |
We can use the Java for-each loop to loop through each element of the arraylist. For example,
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// creating an array list
ArrayList<String> animals = new ArrayList<>();
animals.add("Cow");
animals.add("Cat");
animals.add("Dog");
System.out.println("ArrayList: " + animals);
// iterate using for-each loop
System.out.println("Accessing individual elements: ");
for (String language : animals) {
System.out.print(language);
System.out.print(", ");
}
}
}
Output
ArrayList: [Cow, Cat, Dog]
Accessing individual elements:
Cow, Cat, Dog,
#java