The Complete Guide of ArrayList in Java

arraylist in java

ArrayList in Java is used to store collection of elements /objects that are dynamic. The underlying data structure used in this class is Array but it provides additional functionality in compare to arrays.

 

As we know, arrays are fixed in size, this was the main reason behind introduction of Collection in Java. Contrary to Arrays , an ArrayList grows its size automatically when new elements are added to it and space becomes unavailable.

 

ArrayList in java is part of Java’s collection framework and ArrayList  implements List and RandomAccess interface.

public class ArrayList<E>

extends AbstractList<E>

implements List<E>, RandomAccess, Cloneable, Serializable

arraylist in java

The accessing rate is higher in ArrayList but insertion and deletion is slow. Modification in array is slow because a lot of shifting is required when adding or deleting any value from the ArrayList as it uses array as data structure which is an index based data structure.

 

Some Important points are listed below about ArrayList in Java :

  • ArrayList in java automatically grows its size if any element is being added but the space is unavailable. It also reduce its size when elements are removed from the ArrayList. An ArrayList can be seen as a dynamic array.
  • ArrayList is all about position based storing of elements. It uses array as underlying data structure so every element is added in ArrayList on index. The index starts from 0.
  • One important thing about ArrayList in Java is that it allows duplicate data. Suppose we are adding A,A,B,C,A,D elements into one ArrayList then it is allowed in spite that it contains duplicate elements.
  • ArrayList in Java always maintains the insertion order. The elements will be retrieved from an ArrayList in the same order as it was inserted.
  • ArrayList only allows objects to be stored so Primitive data types cannot be stored in an ArrayList directly. It can be achieved by Auto-Boxing.
  • Java ArrayList is not Thread safe class as it is not synchronized. In an multithreaded environment, ArrayList may produce unexpected outcome if multiple thread access the ArrayList at same time. Still, we can explicitly use synchronize block / method to achieve synchronization.

Example 1: How to create an ArrayList and add new elements

This example illustrates:

  • How to create an ArrayList in java using the default ArrayList() constructor.
  • Add new elements to an ArrayList using the ArrayList add() method.
import java.util.List; 
import java.util.ArrayList; 

public class ArrayListExample { 

public static void main(String[] args) { 

//Below is the code to create an ArrayList of type String 
List<String> friendsCast = new ArrayList<>(); 

//Addition of Elements into the ArrayList 
friendsCast.add("Rachel"); 
friendsCast.add("Ross"); 
friendsCast.add("Phoebe"); 
friendsCast.add("Chandler"); 
friendsCast.add("Monica"); 

//Printing the elements of ArrayList 
System.out.println(friendsCast); 

//Addition of element at a given/specific index in an ArrayList 
friendsCast.add(2, "Janice"); 

//Printing the elements of ArrayList 
System.out.println(friendsCast); 

} }
Output : 
[Rachel,Ross,Phoebe,Chandler,Monica] 
[Rachel,Ross,Janice,Phoebe,Chandler,Monica]

Example 2: How to create an ArrayList from another collection

This example illustrates:

  • How to create an ArrayList in java from another collection using the parameterized constructor ArrayList(Collection c).
  • How to add all the elements from an existing collection to the new ArrayList using the addAll()method of ArrayList.
import java.util.List; 
import java.util.ArrayList;

public class ArrayListExample2 {

public static void main(String[] args) {

List<String> names = new ArrayList<>();

names.add("Rachel"); 
names.add("Ross");

// Code to Create an ArrayList from another existing collection
List<String> extraNames = new ArrayList<>(names);

// Adding some value in the new ArrayList created using the previous ArrayList
extraNames.add("Chandler"); 
extraNames.add("Monica");

List<String> allNames = new ArrayList<>(); 
allNames.add("Joey"); 
allNames.add("Phoebe");

// Adding all elements of one ArrayList into another
allNames.addAll(extraNames);

//Printing the elements of ArrayList 
System.out.println("ArrayList - names - "+names); 
System.out.println("ArrayList - extraNames - "+extraNames); 
System.out.println("ArrayList - allNames - "+allNames);

} }
Output : 
ArrayList - names - [Rachel,Ross] 
ArrayList - extraNames - [Chandler,Monica,Rachel,Ross]
ArrayList - allNames - [Joey,Phoebe,Chandler,Monica,Rachel,Ross]

Example 3: How to access elements from an ArrayList

This example illustrates:

  • How to access the element at a particular index in an ArrayList using the get() method.
  • How to modify the element at a particular index in an ArrayList using the set() method.
  • How to find the size of an ArrayList in java using the size() method.
  • How to check if an ArrayList is empty using the isEmpty() method.
import java.util.ArrayList;
import java.util.List;

public class ArrayListExample2 {

public static void main(String[] args) {
List<String> friendsCast = new ArrayList<>();

// Code to check if an ArrayList is empty
System.out.println("Is the friendsCast list empty? : " + friendsCast.isEmpty());

friendsCast.add("Joey");
friendsCast.add("Ross");
friendsCast.add("Phoebe");
friendsCast.add("Chandler");
friendsCast.add("Rachel");
friendsCast.add("Janice");

// Code to find out the size of an ArrayList
System.out.println("There are total " + friendsCast.size() + " memebers in popular f.r.i.e.n.d.s show");
System.out.println(friendsCast);

// Access the element at a given index
String favouriteChar = friendsCast.get(0);

System.out.println("Favourite Character: " + favouriteChar);

// Change / Modify the element at a given index
friendsCast.set(5, "Monica");

System.out.println("Final and Correct list: " + friendsCast);
}
}
Output :

Is the friendsCast list empty? : true
There are total 6 memebers in popular f.r.i.e.n.d.s show
[Joey, Ross, Phoebe, Chandler, Rachel,Janice]
Final and Correct list: [Joey, Ross, Phoebe, Chandler, Rachel, Monica]

Example 4: How to remove elements from an ArrayList

This example illustrates:

  • How to remove the element at a given index in an ArrayList using remove(int index) method.
  • How to remove an element from an ArrayList using the remove(Object o) method.
  • How to remove all the elements from an ArrayList that exist in a given collection using the removeAll() method.
  • How to clear an ArrayList using clear() method.
import java.util.ArrayList;
import java.util.List;

public class ArrayListExample4 {

public static void main(String[] args) {

List<Integer> numbers = new ArrayList<>();

numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
numbers.add(50);
numbers.add(60);

System.out.println("Numbers List: " + numbers);

// Code to remove the element from particular index
numbers.remove(2);

System.out.println("After executing remove(2): " + numbers);

// Remove the first occurrence of the given element from the ArrayList
// The remove() method returns false if the element does not exist in the ArrayList
boolean isRemoved = numbers.remove(50);

System.out.println("After executing remove(50): " + numbers);

// Remove all the elements from one that exist in another given collection
List<String> numbersToRemove = new ArrayList<>();
numbersToRemove.add(20);
numbersToRemove.add(40);


numbers.removeAll(numbersToRemove);
System.out.println("After removeAll(numbersToRemove): " + numbers);


// Remove all elements from the ArrayList / clear the arraylist
numbers.clear();
System.out.println("After clear(): " + numbers);
}
}
Output :

Numbers List: [10,20,30,40,50,60]
After executing remove(2): [10,20,40,50,60]
After executing remove(50): [10,20,40,60]
After removeAll(numbersToRemove): [10,60]
After Removing all elements that start with "C": [Java]
After clear(): []

Example 5: How to Iterate over an ArrayList

The following example illustrates how to iterate over an ArrayList in java using :

  • Java 8 forEach method and lambda expression.
  • iterator() method.
  • iterator() method and Java 8 forEachRemaining() method.
  • listIterator() method.
  • Simple for-each loop.
  • for loop with index.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class ArrayListExample5
{
public static void main(String[] args) {

List<String> friendsCastExtras = new ArrayList<>();
friendsCastExtras.add("Gunther");
friendsCastExtras.add("Janice");
friendsCastExtras.add("Richard");
friendsCastExtras.add("Mike");

System.out.println("***** Iterate the arraylist using Java 8 forEach and lambda expression *****");
friendsCastExtras.forEach(friendsCastExtras -> {
System.out.println(friendsCastExtras);
});

System.out.println("***** Iterate the arraylist using an iterator() *****");
Iterator<String> friendsIterator = friendsCastExtras.iterator();
while (friendsIterator.hasNext()) {
String friends = friendsIterator.next();
System.out.println(friends);
}

System.out.println("***** Iterate the arraylist using an iterator() and Java 8 forEachRemaining() method *****");
friendsIterator = friendsCastExtras.iterator();
friendsIterator.forEachRemaining(friendsCastExtras -> {
System.out.println(friendsCastExtras);
});

System.out.println("***** How to Iterate the arraylist using a listIterator() to traverse in both the directions *****");

// Here, we start from the end of the list and traverse backwards.
ListIterator<String> friendsIterator2 = friendsCastExtras.listIterator(friendsCastExtras.size());
while (friendsIterator2.hasPrevious()) {
String friendsCast = friendsIterator2.previous();
System.out.println(friendsCast);
}

System.out.println("***** How to Iterate the arraylist using simple for-each loop *****");
for(String friendsCast: friendsCastExtras) {
System.out.println(friendsCast);
}

}
}
Output:

***** Iterate the arraylist using Java 8 forEach and lambda expression *****
Gunther
Janice
Richard
Mike
***** Iterate the arraylist using an iterator() *****
Gunther
Janice
Richard
Mike
***** Iterate the arraylist using an iterator() and Java 8 forEachRemaining() method *****
Gunther
Janice
Richard
Mike
***** How to Iterate the arraylist using a listIterator() to traverse in both the directions *****
Mike
Richard
Janice
Gunther
***** How to Iterate the arraylist using simple for-each loop *****
Gunther
Janice
Richard
Mike

Example 6: How to remove the elements from ArrayList using iterator.remove() method.

The following example illustrates :

  • How to remove elements from an ArrayList while traversing through it using iterator() and listIterator() method.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ArrayListExample6 {

public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);

Iterator<Integer> numbersIterator = numbers.iterator();
while (numbersIterator.hasNext()) {
Integer num = numbersIterator.next();
if(num<30) {
numbersIterator.remove();
}
}

System.out.println(numbers);
}
}
Output:

[30, 40]

Example 7: How to Search for elements in an ArrayList

The below example illustrates:

  • How to Check if an ArrayList in java contains a given element using the contains() method.
  • How to Find the index of the first occurrence of an element in an ArrayList using indexOf() method.
  • How to Find the index of the last occurrence of an element in an ArrayList using lastIndexOf().
import java.util.ArrayList;
import java.util.List;

public class ArrayListExample7 {

public static void main(String[] args) {

List<String> friendsNames = new ArrayList<>();

friendsNames.add("Bing");
friendsNames.add("Tribbiani");
friendsNames.add("Green");
friendsNames.add("Geller");
friendsNames.add("Buffay");
friendsNames.add("Geller");

// Code to Check if an ArrayList contains a given element
System.out.println("Does friendsNames array contains \"Bing\"? : " + friendsNames.contains("Bing"));

// How to Find the index of the first occurrence of an element in an ArrayList
System.out.println("indexOf \"Geller\": " + names.indexOf("Geller"));
System.out.println("indexOf \"Bing\": " + names.indexOf("Bing"));

// Find the index of the last occurrence of an element in an ArrayList
System.out.println("lastIndexOf \"Geller\" : " + names.lastIndexOf("Geller"));
System.out.println("lastIndexOf \"Tribbiani\" : " + names.lastIndexOf("Tribbiani"));
}
}
Output :

Does friendsNames array contain "Bing"? : true
indexOf "Geller": 3
indexOf "Bing": 0
lastIndexOf "Geller" : 5
lastIndexOf "Chandler" : -1

Example 8 : How to create ArrayList of user defined objects

This example illustrates :

  • How to create ArrayList of user-defined objects using Generics.
import java.util.ArrayList;
import java.util.List;

class Employee {
private String empName;
private int empAge;

public User(String empName, int empAge) {
this.empName = empName;
this.empAge = empAge;
}

public String getName() {
return empName;
}

public void setName(String empName) {
this.empName = empName;
}

public int getAge() {
return empAge;
}

public void setAge(int empAge) {
this.empAge = empAge;
}
}

public class ArrayListExample8 {
public static void main(String[] args) {

//Creating List of Employee type using Genrics
List<Employee> employees = new ArrayList<>();

employees.add(new Employee("Mindy", 25));
employees.add(new Employee("Richard", 34));
employees.add(new Employee("Barry", 29));

employees.forEach(employee -> {
System.out.println("Emp Name : " + employee.getName() + ", Emp Age : " + employee.getAge());
});
}
}
Output :

Emp Name : Mindy, Emp Age : 25
Emp Name : Richard, Emp Age : 34
Emp Name : Barry, Emp Age : 29

Example 9 : How to Sort an ArrayList in Java

This example illustrates :

  • How to Sort an ArrayList using Collections.sort() method.
  • How to Sort an ArrayList using ArrayList.sort() method.
  • How to Sort an ArrayList of user defined objects with a custom comparator.

9.1 : How to Sort an ArrayList using Collections.sort() method.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ArrayListExample91 {

public static void main(String[] args) {

List<Integer> numbers = new ArrayList<>();

numbers.add(5);
numbers.add(4);
numbers.add(1);
numbers.add(3);
numbers.add(2);

System.out.println("Before : " + numbers);

// Code for Sorting an ArrayList using Collections.sort() method
Collections.sort(numbers);

System.out.println("After : " + numbers);
}
}
Output :

Before : [5, 4, 1, 3, 2]
After : [1, 2, 3, 4, 5]

9.2 : How to Sort an ArrayList using ArrayList.sort() method.

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class ArrayListExample92 {

public static void main(String[] args) {

List<String> names = new ArrayList<>();

names.add("Adam");
names.add("David");
names.add("Bob");
names.add("Courtney");

System.out.println("Names : " + names);

// Sort an ArrayList using its own sort() method. Note : You must pass a Comparator to the ArrayList.sort() method.
names.sort(new Comparator<String>() {
@Override
public int compare(String name1, String name2) {
return name1.compareTo(name2);
}
});

// Or the above code can also be written simply using lambda expression
names.sort((name1, name2) -> name1.compareTo(name2));

// Or Simply use below code
names.sort(Comparator.naturalOrder());

System.out.println("Sorted Names List : " + names);
}
}
Output :

Names : [Adam, David, Bob, Courtney]
Sorted Names List : [Adam, Bob, Courtney, David]

9.3 :  How to Sort an ArrayList of user defined objects with a custom comparator.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Employee {
private String name;
private Integer age;

public Person(String name, Integer age) {
this.name = name;
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

@Override
public String toString() {
return "{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}

public class ArrayListExample93 {

public static void main(String[] args) {

List<Employee> employee = new ArrayList<>();
employee.add(new Employee("Bob", 47));
employee.add(new Employee("Adam", 34));
employee.add(new Employee("John", 25));
employee.add(new Employee("David", 31));

System.out.println("Employee List : " + employee);

// Sort employees by their Age
employee.sort((empl1, empl2) -> {
return empl1.getAge() - empl2.getAge();
});

// Or simply use below code
employee.sort(Comparator.comparingInt(Employee::getAge));

System.out.println("Sorted Employee List by Age : " + employee);

// Or You can also sort using Collections.sort() method by passing the custom Comparator
Collections.sort(employee, Comparator.comparing(Employee::getName));

System.out.println("Sorted Employees List by Name : " + employee);
}
}
Output :

Employee List : [{name='Bob', age=47}, {name='Adam', age=34}, {name='John', age=25}, {name='David', age=30}]
Sorted Employee List by Age : [{name='John', age=25}, {name='David', age=30}, {name='Adam', age=34}, {name='Bob', age=47}]
Sorted Employees List by Name : [{name='Adam', age=34}, {name='Bob', age=47}, {name='David', age=30}, {name='John', age=25}]

Example 10 : How to Synchronizing Access to an ArrayList / Make ArrayList thread-safe.

The ArrayList class is not a thread-safe class as it is not synchronized. If multiple threads try to modify an ArrayList at the same time then the final result becomes inconsistent because one thread might override the changes done by another thread.

10.1 : ArrayList’s unpredictable behaviour in multithreaded environment.

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ArrayListExample10 {

public static void main(String[] args) throws InterruptedException {

List<Integer> al = new ArrayList<>();
al.add(1);
al.add(2);
al.add(3);

// Code to Create a thread pool of size 10
ExecutorService executorService = Executors.newFixedThreadPool(10);

// Code to Create a Runnable task that increments each element of the ArrayList by one
Runnable task = () -> {
incrementArrayList(al);
};

// Code to Submit the task to the executor service 100 times.
// Note :All the tasks will modify the ArrayList concurrently
for(int i = 0; i < 100; i++) {
executorService.submit(task);
}

executorService.shutdown();
executorService.awaitTermination(60, TimeUnit.SECONDS);

System.out.println(al);
}

// Increment all the values in the ArrayList by one
private static void incrementArrayList(List<Integer> al) {
for(int i = 0; i < al.size(); i++) {
Integer value = al.get(i);
al.set(i, value + 1);
}
}
}

If ArrayList was thread-safe then the final output of the above program should be equal to [101, 102, 103] because we’re incrementing the values in the ArrayList 100 times using executorService.

But as ArrayList is not synchronized, it will produce different result in each execution.

Output :

[96, 96, 98]

10.2 : Synchronizing access to an ArrayList.

The below example solves the problem mentioned in previous example :

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ArrayListExample11 {

public static void main(String[] args) throws InterruptedException {

List<Integer> al = Collections.synchronizedList(new ArrayList<>());
al.add(1);
al.add(2);
al..add(3);

ExecutorService executorService = Executors.newFixedThreadPool(10);

Runnable task = () -> {
incrementArrayList(al);
};


for(int i = 0; i < 100; i++) {
executorService.submit(task);
}

executorService.shutdown();
executorService.awaitTermination(60, TimeUnit.SECONDS);

System.out.println(al);
}


private static void incrementArrayList(List<Integer> al) {
synchronized (al) {
for (int i = 0; i < al.size(); i++) {
Integer value = safeAlrrayList.get(i);
al.set(i, value + 1);
}
}
}
}
Output :
[101, 102, 103]

The above example illustrate the uses of Collections.synchronizedList() method to get a synchronized view of the ArrayList.

Please also note that , the modifications to the ArrayList inside the incrementArrayList() method is wrapped inside a synchronized block. This ensures that no two threads can increment ArrayList elements at the same time.

You can also use a CopyOnWriteArrayList if you need thread safety. It is a thread-safe version of the ArrayList class. It implements all the mutating operations by making a fresh copy of the ArrayList.

Watch this video “What is ArrayList in Java” (10 min 58 sec)

Conclusion

You have learned about what is ArrayList in java, how to create the ArrayList from existing collection, how to create an ArrayList,how to modify, add and remove items from an ArrayList, how to iterate an ArrayList,  sort an ArrayList, and  synchronize an ArrayList.

Leave a Reply

Your email address will not be published. Required fields are marked *