This free course describes the Java ArrayList class and its operations like add, remove, search, and sort elements. It is available under the java.util
package.
A Simple Introduction to ArrayList in Java
Java ArrayList is a dynamic array that adjusts its size accordingly as elements get added or removed. The native array type has a fixed length and doesn’t allow resizing. You can’t add/remove values from it. To do so, one has to create a new object. On the contrary, the ArrayList grows or shrinks its size automatically as the elements pop in or out.
ArrayList is defined under Java’s collection framework and implements the List interface. Let’s check it out in detail and with the help of examples.
The following are the points that we are discussing in this Java ArrayList tutorial. Let’s check them out one by one.
Also Read: Interfaces in Java – OOP Concept
Understand ArrayList in Java
Java provides a wide variety of abstract data structures for better control over data and its features. The ArrayList in Java is one such data structure that is extended by AbstarctList and further implements the List interface.
Java ArrayList and the arrays have a common property as both store data in a linear format. It means you can access any element from the base address of the first entry in the ArrayList or array.
Standard Java arrays have a predefined fixed length. They can’t be made to expand or shrink once they are defined. It means the programmer must be sure of how many entries the array needs to store. Hence, they are static by nature.
If you need to work with a dynamic data structure with similar properties as arrays, then use ArrayLists. They have a minimum initial size during their creation. Eventually, the list expands as more entries get added. Similarly, it shrinks when data entries get removed from the list.
Create Java ArrayList
Before starting to use the ArrayList, you must import the ArrayList library first. The imported library works for Generic Class E. It means you can use the ArrayList to hold data of any type. E can refer to Integer, String, or Boolean.
ArrayList<E> al = new ArrayList<>();
If you wish to use a predefined size for the ArrayList, then specify that too in the definition.
ArrayList<E> al = new ArrayList<>(n);
Where n is the capacity of the ArrayList, and it can grow as the user keeps on adding more elements to the list.
Dos and Don’t
Here are some handful of facts about ArrayList in Java.
- Java ArrayList is a dynamic array, also called a resizable array. It adjusts (meaning expands/shrinks) itself automatically upon element addition/removal.
- It is a wrapper over arrays that it uses to store the elements. Therefore, it allows access using index values.
- The ArrayList doesn’t check for duplicate or null values.
- It is an ordered collection and preserves the insertion order by default.
- You can’t create an ArrayList from native types such as int, char, etc. Instead, use boxed types such as Integer, Double, Character, Boolean, etc.
- Java ArrayList is not threadsafe. The programmer should take care of synchronization while accessing ArrayList from multiple threads.
Also Read: How to Use Java String Format with Examples
Add Elements
In this section, you’ll see how to create an ArrayList in a Java program. The first step is to define an object of the ArrayList class and initialize it using the constructor method.
Below is an example that creates the ArrayList and adds elements using the add() method.
The add () method has this syntax:
# ArrayList add() method i. add(int index, Obejct obj) : Index where to add object, the object. ii. add(Obejct obj) : Object to be added to the end.
Now, check out the example.
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
// Define an ArrayList of Week days
List test = new ArrayList<>();
// Adding new elements to the ArrayList
test.add("1A");
test.add("2A");
System.out.println(test);
// Adding an element at the zeroth index
test.add(0, "0A");
System.out.println(test);
}
}
Initialize ArrayList
If there is an existing ArrayList with some elements, you can use it to initialize another object. Also, you can add another collection to an existing ArrayList.
In the below example, we first created an ArrayList object and added a few elements to it. After that, the same variable is used as a seed to generate another ArrayList.
import java.util.ArrayList;
import java.util.List;
public class Init {
public static void main(String[] args) {
List old = new ArrayList<>();
old.add(1);
old.add(2);
old.add(3);
System.out.println("Old ArrayList: " + old);
// Let's create a new ArrayList from existing ArrayList
List new = new ArrayList<>(old);
new.add(4);
new.add(5);
new.add(0,1); // add element 1 at index 0
System.out.println("New ArrayList: " + new);
// Difference between add(index, element) and add(element)
// The first one throws an error - index is out of bound
}
}
Get Elements
Get() method to access elements from an ArrayList:
# ArrayList get() method get(index)
The example below shows the get operations of the ArrayList.
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
public class Test {
public static void main(String args[]) {
ArrayList al = new ArrayList<>();
al.add(0,1); // add element 1 at index 0 and so on
al.add(2);
al.add(2,3);
System.out.println(al.get(1));
// Returns the element at specfied index
}
}
Remove Elements
In this section, you’ll see how to use ArrayList in a Java program. First of all, you’ll create an ArrayList object and call the add()/remove()/get() method to insert/delete/access its elements.
Remove() method syntax is as follows:
# ArrayList remove() method i. remove(int index) : Index of the object to be removed. ii. remove(Obejct obj) : Object to be removed.
The example below shows the add and remove operations of the ArrayList.
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
public class Test {
public static void main(String args[]) {
ArrayList al = new ArrayList<>();
al.add(0,1); // add element 1 at index 0 and so on
al.add(2);
al.add(2,3);
al.remove(1);
// Removes the element at the index 1
al.clear(); // Removes all the element from the list
}
}
Traverse ArrayList
Java provides multiple ways to traverse an ArrayList. You can watch out for some of the approaches below, and later, the example shows how to use them to iterate the ArrayList.
- Standard Java for loop
- Standard While loop in Java
- Enhanced Java for loop (a.k.a. advanced for loop)
- Java ArrayList
forEach
method - Iterator approach
import java.util.ArrayList;
import java.util.Iterator;
public class Test {
public static void main(String[] args) {
ArrayList<String> books = new ArrayList<String>();
books.add("Python");
books.add("Java");
books.add("Go");
books.add("PHP");
System.out.println("\n*** Traverse ArrayList using Java for loop ***");
for(int i = 0; i < books.size(); i++) {
System.out.println(books.get(i));
}
System.out.println("\n*** Traverse ArrayList using While loop in Java ***");
int j = 0;
while(j < books.size()) { System.out.println(books.get(j++)); }
System.out.println("\n*** Iterate ArrayList using Enhanced Java for loop ***");
for(String book: books) { System.out.println(book); }
System.out.println("\n*** Iterate Java ArrayList using its forEach method ***");
books.forEach((book) -> System.out.println(book));
System.out.println("\n*** Traverse Using the Standard Iterator() Approach ***");
Iterator bookIterator = books.iterator();
while (bookIterator.hasNext()) {
System.out.println(bookIterator.next());
}
}
}
After execution, the output is:
*** Quick Traversal Using forEach and Lambda (Java 8) *** Python Java Go PHP *** Traverse Using the Standard Iterator() Approach*** Python Java Go PHP *** Using the Standard iterator() and forEachRemaining() (Java 8) *** Python Java Go PHP *** Using ListIterator to Traverse ArrayList (bidirectional) *** PHP Go Java Python *** Traverse via Regular for Loop *** Python Java Go PHP *** Traverse in a C-style for Loop with indices *** Python Java Go PHP
Search Elements
Java ArrayList class provides various methods to search for elements. These are as follows:
- Contains() – It returns true if the element exists in ArrayList, false otherwise.
- IndexOf() – It returns the index of the first occurrence of an element.
- LastIndexOf() – Returns the index of the final occurrence of an element.
Check out the below Java ArrayList example:
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<String> arr = new ArrayList<String>();
arr.add("Sunday");
arr.add("Monday");
arr.add("Tuesday");
arr.add("Wednesday");
arr.add("Thursday");
arr.add("Friday");
arr.add("Saturday");
arr.add("Sunday");
// Find if an ArrayList contains a specific element
System.out.println("Does arr List Contain \"Monday\"? : " + arr.contains("Monday"));
// Find the first position of an element in the ArrayList
System.out.println("First Index Of \"Wednesday\": " + arr.indexOf("Wednesday"));
System.out.println("First index Of \"Sunday\": " + arr.indexOf("Sunday"));
// Find the last position of an element in the ArrayList
System.out.println("Last Index Of \"Sunday\" : " + arr.lastIndexOf("Sunday"));
}
}
The output is:
Does arr List Contain "Monday"? : true
First Index Of "Wednesday": 3
First index Of "Sunday": 0
Last Index Of "Sunday" : 7
User-defined ArrayList
An ArrayList is a generic container. Therefore, it can hold all kinds of data such as all built-in types (Integer, Double, String, etc.), ArrayList, or any user-defined types.
In the below example, you’ll see how we create an ArrayList of user-defined (UDT) type.
import java.util.ArrayList;
class Book {
private String author;
private String subject;
public Book(String author, String subject) {
this.author = author;
this.subject = subject;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
}
public class Test {
public static void main(String[] args) {
ArrayList<Book> Books = new ArrayList<Book>();
Books.add(new Book("Zed A. Shaw", "Python"));
Books.add(new Book("Herbert Schildt", "Java"));
Books.add(new Book("David Powers", "PHP"));
Books.forEach(Book -> System.out.println("Author : " + Book.getAuthor() + ", Subject : " + Book.getSubject()));
}
}
The output is:
Author : Zed A. Shaw, Subject : Python Author : Herbert Schildt, Subject : Java Author : David Powers, Subject : PHP
Sort Elements
Sorting is a quite frequent activity that programmers need to do while programming. Java provides some innovative ways to sort the data in ArrayList.
- Collections.sort()
- ArrayList.sort()
- User-defined sorting
Let’s illustrate the sorting of Java ArrayList using an example.
import java.util.ArrayList;
import java.util.Collections;
public class Test {
public static void main(String[] args) {
ArrayList<Integer> num = new ArrayList<Integer>();
num.add(44);
num.add(22);
num.add(11);
num.add(33);
num.add(55);
num.add(66);
num.add(22);
System.out.println("List prior to sorting : " + num);
// Sort the ArrayList
Collections.sort(num);
System.out.println("List after sorting : " + num);
}
}
The result:
List prior to sorting : [44, 22, 11, 33, 55, 66, 22] List after sorting : [11, 22, 22, 33, 44, 55, 66]
Un-synchronized ArrayList
The ArrayList class is not thread-protected by default. If multiple threads update an ArrayList simultaneously, the result may become non-deterministic. It is because the changes by one thread may get overridden by another.
To observe this behavior, let’s first consider an example where multiple threads try to modify an ArrayList. If you need, check out our in-depth tutorial on multithreading in Java.
This example intends to highlight the problem with ArrayList in a multi-threaded program.
import java.util.ArrayList;
import java.util.concurrent.*;
public class Test {
public static void main(String[] args) throws InterruptedException {
ArrayList<Integer> shared = new ArrayList<Integer>();
shared.add(0);
shared.add(0);
shared.add(0);
shared.add(0);
shared.add(0);
// Set up thread pool with 5 threads
ExecutorService execService = Executors.newFixedThreadPool(5);
// Add a task for decrementing the list elements by one
Runnable task = () -> {updateList(shared);};
// Run the task 999 times to update the list, all at once
for(int i = 0; i < 999; i++) {
execService.submit(task);
}
execService.shutdown();
execService.awaitTermination(60, TimeUnit.SECONDS);
System.out.println(shared);
}
// Update ArrayList by subtracting one from each element
private static void updateList(ArrayList<Integer> shared) {
for(int i = 0; i < shared.size(); i++) {
Integer value = shared.get(i);
shared.set(i, value - 1);
}
}
}
The output is:
[-985, -995, -981, -907, -996]
The expected result was [-999, -999, -999, -999, -999], but what we get is [-985, -995, -981, -907, -996].
Synchronize ArrayList
Let’s see how to protect ArrayList when multiple threads try to read it in real-time. We have shown how to do it in the following example.
import java.util.ArrayList;
import java.util.concurrent.*;
public class Test {
public static void main(String[] args) throws InterruptedException {
ArrayList<Integer> shared = new ArrayList<Integer>();
shared.add(0);
shared.add(0);
shared.add(0);
shared.add(0);
shared.add(0);
// Set up thread pool with 5 threads
ExecutorService execService = Executors.newFixedThreadPool(5);
// Prepare a Runnable task for decrementing the list elements by one
Runnable task = () -> {updateList(shared);};
// Run the task 999 times to update the list, all at once
for(int i = 0; i < 999; i++) {
execService.submit(task);
}
execService.shutdown();
execService.awaitTermination(60, TimeUnit.SECONDS);
System.out.println(shared);
}
// Update ArrayList by subtracting one from each element
private static void updateList(ArrayList<Integer> shared) {
synchronized(shared) {
for(int i = 0; i < shared.size(); i++) {
Integer value = shared.get(i);
shared.set(i, value - 1);
}
}
}
}
We used Collections.synchronizedList() function to enable synchronization for the ArrayList. Also, we defined the updateArrayList()
method, which modifies the ArrayList in a synchronized manner.
The result of the above sample code is as follows:
[-999, -999, -999, -999, -999]
Java ArrayList Quick Q&A
Here are some quick questions and answers to refresh your knowledge of ArrayList.
Arrays don’t have built-in sorting or searching support.
ArrayList can contain mixed objects, whereas Arrays can only hold similar data.
An array is of pre-defined size and reserves memory in advance.
ArrayList provides a toArray() method to return an array of elements.String array[] = arrayList.toArray();
The fastest to find duplicates is by copying the ArrayList elements to a Set. And then determine the difference between the length of ArrayList and Set. It is the nature of the Set that it doesn’t accept duplicates. Hence, it’ll exclude all of them.
The list is a Java interface, whereas ArrayList is a class implementing the List type.
Arrays are of static size, but ArrayList is of variable length.
ArrayList can only have object elements but can be of different types.
The array has a length attribute, whereas ArrayList provides a size() method.
ArrayList uses arrays, whereas LinkedList gets a doubly-linked list to store elements.
Updating an ArrayList is slower than a LinkedList. ArrayList is better when it comes to storing and searching. However, the LinkedList is good at manipulating data.
Before You Leave
Today, we covered an important concept in Java which is ArrayList. It is an essential topic to learn for serious programmers. It has O(n) performance and is faster than its counterparts, such as Vector, LinkedList, and HashMap.
Lastly, our site needs your support to remain free. Share this post on social media (Linkedin/Twitter) if you gained some knowledge from this tutorial.
Thanks,
TechBeamers