How to initialize an ArrayList in Java
ArrayList in Java is the most commonly used data structure for creating a dynamic size array. It extends the Abstract class and implements the Java List interface. The main difference between array and ArrayList is that the array is static(we cannot add or remove elements) while ArrayList is dynamic(we can add, remove or modify elements). In this article, we will see what is ArrayList and how to initialize an ArrayList in Java?
You might also be interested in ArrayList vs LinkedList
Declaring an ArrayList Class in Java
In order to use ArrayList in Java, we must import java.util.ArrayList. Below is the declaration of an ArrayList
public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable,Serializable
where E denotes the element or Object type (Eg: Integer, String, etc)
The ArrayList class extends the AbstractList class and implements the List interface.
We can create ArrayList in Java Constructors in the below 3 methods:
- It is a resizeable dynamic array where we can add, modify or remove elements any time from the list
- Maintains a sequential order.
- It is easy to access any data from the list based on the index.
- Allows duplicate elements in the list
In addition to the below methods, ArrayList in Java has access to all methods of the List interface.
Java ArrayList Generic and Non-Generic Declaration
Before JDK 1.5, the Java Collection framework was generic as described below.
ArrayList al = new ArrayList(); --> List can hold any type of element
After JDK 1.5, it supports non-generic which can be used as below. We can specify the element type within .
ArrayList al = new ArrayList(); --> List can contain only String values
ArrayList al = new ArrayList(); --> List can contain only Integer value
Java ArrayList Exceptions
ArrayList in Java throws below exceptions:
- UnsupportedOperationException - when the operation is not supported
- IndexOutofBoundsException - when invalid index is specified (fromIndex toIndex or toIndex>size)
- ClassCastException - when the class of the specified element prevents to add it to the list
- NullPointerException - when the specified element is null and the list does not allow to add null elements
- IllegalArgumentException - when some property of the element prevents to add to the list
Before we start using the ArrayList class, we need to import the relevant package in order to use it. For this, we import the below package to use the ArrayList.
import java.util.ArrayList;
Declare an ArrayList in Java
We can declare an ArrayList in Java by creating a variable of ArrayList type. We can also specify the type of list as either String or Integer, etc. Below is an example of declaring an ArrayList of String and Integer type.
ArrayList colors;
ArrayList weight;
Create an ArrayList in Java
Once we declare an ArrayList, we can create it by invoking the constructor to instantiate an object and assign it to the variable. We can use any of the constructors as discussed above. We can also declare and create an ArrayList in a single statement as below.
ArrayList colors = new ArrayList();
(OR)
ArrayList colors; //declare an ArrayList
colors = new ArrayList(); //create an ArrayList
How to initialize an ArrayList in Java?
Once we declare and create an ArrayList, we can initialize it with the required values. There are several methods to initialize an ArrayList as mentioned below.
Using add() method
One common method to initialize an ArrayList in Java is by using the add() method.
ArrayList colors = new ArrayList();
colors.add("Red");
colors.add("Blue");
colors.add("Green");
Using asList() method
We can use the asList() method of the Arrays class while creating an ArrayList. This is another method to initialize an ArrayList.
ArrayList color = new ArrayList(
Arrays.asList("Red","Blue","Green")
);
Using List.Of() method
The List.of() method is another way to initialize an ArrayList.
List colors = new ArrayList(
List.of("Red","Blue","Green")
);
Using another Collection
We can also initialize an ArrayList using the values of another Collection. In the below code, we initialize the data variable with colors ArrayList values.
ArrayList colors = new ArrayList();
colors.add("Red");
colors.add("Blue");
colors.add("Green");
ArrayList data = new ArrayList(colors);
Creating ArrayList and add elements and collection
First, we create an ArrayList in Java of type String and then add elements to the list. Then we add a new element at index 1. Thus, the element which was previously present at index 1 will move sequentially to the right. The index in an array always starts at 0.
Next, we create a new list with 2 elements and add the entire collection to list 1 at index 1.
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String args) {
//Create a String ArrayList
ArrayList al = new ArrayList();
//Add elements
al.add("Java");
al.add("JavaScript");
al.add("PHP");
System.out.println("Element in the list1:");
System.out.println(al);
//Add element at index 1
al.add(1, "C");
System.out.println("After adding element at index 1: ");
System.out.println(al);
//Create list2
ArrayList list = new ArrayList();
list.add("C++");
list.add("Ruby");
System.out.println("Elements in list2:");
System.out.println(list);
//Add list2 elements in list1
al.addAll(1, list);
System.out.println("Elements in List 1 after adding list2:");
System.out.println(al);
}
}
Output:
Element in the list1:
After adding element at index 1:
Elements in list2:
Elements in List 1 after adding list2:
Modifying and Removing an element from ArrayList
Below is an example program to modify the array list and remove an element from ArrayList in Java.
import java.util.ArrayList;
public class ArrayListDemo2 {
public static void main(String args) {
//Create an Integer ArrayList
ArrayList numbers = new ArrayList();
numbers.add(4);
numbers.add(8);
numbers.add(2);
System.out.println("Elements in the list are: ");
System.out.println(numbers);
//Modify element
numbers.set(1, 6);
System.out.println("After modifying an element at index 1:");
System.out.println(numbers);
//Remove an element
numbers.remove(2);
System.out.println("After removing an element at index 2:");
System.out.println(numbers);
}
}
Output:
Elements in the list are:
After modifying an element at index 1:
After removing an element at index 2:
Other useful methods
The below example illustrates the usage of contains(), indexOf(), and retainAll() methods which are part of the ArrayList.
import java.util.ArrayList;
public class ArrayListDemo4 {
public static void main(String args) {
ArrayList letters = new ArrayList();
letters.add("A");
letters.add("G");
letters.add("R");
System.out.println(letters.contains("U"));
int i = letters.indexOf("G");
System.out.println("Index of G is " + i);
ArrayList c = new ArrayList();
c.add("F");
c.add("E");
c.add("T");
c.add("P");
letters.addAll(c);
System.out.println("Elements in the list after using addAll:");
System.out.println(letters);
letters.retainAll(c);
System.out.println("Elements in the list after using retainAll:");
System.out.println(letters);
}
}
Output:
false
Index of G is 1
Elements in the list after using addAll:
Elements in the list after using retainAll:
Clear an ArrayList in java
The below example clearly shows the result of using isEmpty() and clear() methods in ArrayList. Using the clear() method, we can empty the ArrayList by removing all the elements.
import java.util.ArrayList;
public class ArrayListDemo5 {
public static void main(String args) {
ArrayList s = new ArrayList();
s.add("India");
s.add("US");
s.add("Germany");
System.out.println("Contents in list:");
System.out.println(s);
System.out.println("Result of calling isEmpty(): " + s.isEmpty());
s.clear();
System.out.println("Contents in list after calling clear(): " + s);
System.out.println("Result of calling isEmpty() after clear: " + s.isEmpty());
}
}
Contents in list:
Result of calling isEmpty(): false
Contents in list after calling clear():
Result of calling isEmpty() after clear: true
ensureCapacity()
This method ensures that the Java ArrayList can hold a minimum number of elements. This can be used for a dynamically growing array size.
import java.util.ArrayList;
public class ArrayListDemo6 {
public static void main(String args) {
ArrayList al = new ArrayList();
al.add("Mango");
al.add("Guava");
al.add("Apple");
al.ensureCapacity(3);
System.out.println("Array list can store minimum of 3 elements");
al.add("Orange");
System.out.println(al);
}
}
Output:
Array list can store minimum of 3 elements
Print ArrayList in Java - Iterate or navigate through elements
We can iterate through an ArrayList in Java using any one of the below methods:
- For loop
- For each
- Iterator interface
- ListIterator interface
Get elements using for loop
Here, we use for loop to retrieve array elements and print them in output.
import java.util.ArrayList;
public class ArrayListDemo3 {
public static void main(String args) {
ArrayList list = new ArrayList();
list.add("Ramesh");
list.add("Banu");
list.add("Priya");
list.add("Karthik");
int size = list.size();
System.out.println("Size of list is : " + size);
for(int i=0;i
Read the full article