ArrayList in Java


ArrayList Java Java ListViews 4735

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

Java ArrayList Hierarchy

Arraylist in java

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<E> extends AbstractList<E> implements List<E>, 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.

ArrayList Constructors

We can create ArrayList in Java Constructors in the below 3 methods:

ConstructorDescription
ArrayList()This creates an empty array list
ArrayList(Collection c)This creates an array list with the elements of collection
ArrayList(int size)This creates an array list of specific size

Java ArrayList Features

  • 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

Java ArrayList Methods

In addition to the below methods, ArrayList in Java has access to all methods of the List interface.

MethodDescriptionParameter
Boolean add(Object e)Adds the specified element to the end of list.e - the element to be added.
Return value - True
void add(int index, Object e)Adds the element to the specified index. If the index already contains an element, it is shifted to the rightindex- the index at which the element needs to be inserted
e - the element which needs to be inserted
Boolean addAll(Collection c)Adds a collection of specified elements to the list.c - collection of elements to be added
Return value - true
Boolean addAll(int index, Collection c)Adds a collection of elements at the specified index. If the index already contains element, it is subsequently shifted to the rightindex - index at which the elements needs to be added
c - collection of elements to be added
Return value - True
void clear()Clears all the elements in the list.
Boolean contains(Object o)Checks if the list contains the specified elementReturn value - true if the list contains the element
Boolean containsAll(Collection c)Checks if the list contains all the elements in the collectionReturn value - true if the list contains all the elements
Boolean equals(Object o)Compares if the list contains all the specified elements in the exact orderReturn value - true if object elements match with the list
Object getIndex(int index)Retrieves the element at the specified indexindex - the index at which the element that needs to be retrieved
Return value - The element at the specified index
int indexOf(Object o)Fetches the index of the first occurrence of the specified elemento - The element to be identified
Return value - index value
Boolean isEmpty()Checks if the list is empty or notReturn value - true if list contains no values
Iterator iterator()Retrieves the iterator of list in sequenceReturn value - Iterator
int lastIndexOf(Object o)Retrieves the last occurrence of the specified objecto - Element to be identified
Return value - index value
Object remove(int index)Removes the element at the specified indexindex - index position at which the element has to be removed
Return value - The element that is removed
Boolean remove(Object o)Removes the first occurrence of the specified object from the list if presento - The element that needs to be removed
Return value - true if list contains the element
Boolean removeAll(Collection c)Removes the first occurrence of all the elements in the collection from the list if presentc - collection of elements
Return value - true if the list contains the collection
Boolean retainAll(Collection c)Retains all the elements specified in collection in list. Other elements will be removedc - collection of elements that has to be retained
Return value - true if the list changed due to the method called
Object set(int index, Object o)Replaces the element at the specified index with the object passedo - the element to be replaced
index - index of the element
Return value - Returns the element which was previously at the specified index
int size()Fetches the size of the listReturn value - size of the list
List sublist(int fromIndex, int toIndex)Retrieves the part of the list based on start and endIndexfromIndex - position from which the sublist has to be retrieved (included)
toIndex - the index until which the sublist has to be retrieved (excluded)
void ensureCapacity(int mincapacity)Increases the size of arraylist and ensures it can hold minimum capacity as mentionedmincapacity - minimum number of elements the arraylist can hold
void sort(Comparator c)Sorts the elements in the list based on the comparator argumentc - compartor which is used to compare the list elements
Object[] toArray()Returns an array of elements in proper sequenceReturn value - Array of all elements in the list in proper sequence
String toString()Returns a String representation of the array elements collectionReturn value - String of array elements separated by comma and space and enclosed within []
void trimToSize()Trims the size of ArrayList instance to current list size

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<String> al = new ArrayList<String>(); –> List can contain only String values

ArrayList<Integer> al = new ArrayList<Integer>(); –> 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<0 or 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

Import ArrayList in Java

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<String> colors;
ArrayList<Integer> 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<String> colors = new ArrayList<String>();

(OR)

ArrayList<String> colors; //declare an ArrayList
colors = new ArrayList<String>(); //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<String> colors = new ArrayList<String>();
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<String> color = new ArrayList<String>(
  Arrays.asList("Red","Blue","Green")
);

Using List.Of() method

The List.of() method is another way to initialize an ArrayList.

List<String> 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<String> colors = new ArrayList<String>();
colors.add("Red");
colors.add("Blue");
colors.add("Green");
    
ArrayList<String> data = new ArrayList<String>(colors);

Java ArrayList Examples

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<String> al = new ArrayList<String>();
    
    //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<String> list = new ArrayList<String>();
    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:
[Java, JavaScript, PHP]
After adding element at index 1: 
[Java, C, JavaScript, PHP]
Elements in list2:
[C++, Ruby]
Elements in List 1 after adding list2:
[Java, C++, Ruby, C, JavaScript, PHP]

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<Integer> numbers = new ArrayList<Integer>();
    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: 
[4, 8, 2]
After modifying an element at index 1:
[4, 6, 2]
After removing an element at index 2:
[4, 6]

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<String> letters = new ArrayList<String>();
    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<String> c = new ArrayList<String>();
    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:
[A, G, R, F, E, T, P]
Elements in the list after using retainAll:
[F, E, T, P]

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<String> s = new ArrayList<String>();
    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:
[India, US, Germany]
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
[Mango, Guava, Apple, Orange]

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<String> list = new ArrayList<String>();
    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<size;i++)
    {
      System.out.println(list.get(i));
    }
  }

}
Output:
Size of list is : 4
Ramesh
Banu
Priya
Karthik

 Get elements using For each loop

We can also use the for-each loop to get the array elements as described below.

import java.util.ArrayList;
public class ArrayListDemo3 {

  public static void main(String[] args) {
    
    ArrayList<String> list = new ArrayList<String>();
    list.add("Ramesh");
    list.add("Banu");
    list.add("Priya");
    list.add("Karthik");

    for(String s: list)
    {
      System.out.println(s);
    }
  }

}
Output:
Ramesh
Banu
Priya
Karthik

Traverse using Iterator and ListIterator

Iterator and ListIterator are other methods of traversing through array elements in Java ArrayList. For this, we first create an ArrayList and use that object to create an iterator object or ListIterator object. We can then use the in-built methods like next() to get the elements by iterating using while loop. We can also traverse backward, by using the previous() method.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class ArrayListIterator {

  public static void main(String[] args) {
    ArrayList<String> cities = new ArrayList<String>();
    cities.add("Bangalore");
    cities.add("Chennai");
    cities.add("Delhi");
    cities.add("Mumbai");
    cities.add("Hyderabad");
    
    System.out.println("Traversing forward using iterator");
    Iterator<String> it = cities.iterator();
    while(it.hasNext()) {
      System.out.println(it.next());
    }
    
    System.out.println("\nTraversing reverse using listiterator");
    ListIterator<String> li = cities.listIterator(cities.size());
    while(li.hasPrevious()) {
      System.out.println(li.previous());
    }
    
  }

}
Output:
Traversing forward using iterator
Bangalore
Chennai
Delhi
Mumbai
Hyderabad

Traversing reverse using listiterator
Hyderabad
Mumbai
Delhi
Chennai
Bangalore

Sort an ArrayList in Java

We can sort elements in the array list using the Java Collection framework’s sort method as illustrated below. Here we are sorting integer numbers present in the ArrayList.

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

public class ArrayListSort {

  public static void main(String[] args) {
    ArrayList<Integer> i = new ArrayList<Integer>();
    i.add(5);
    i.add(1);
    i.add(10);
    i.add(3);
    i.add(8);
    System.out.println("Before Sorting");
    for(int num : i)
      System.out.println(num);
    Collections.sort(i);
    System.out.println("After Sorting");
    for(int numbers : i)
      System.out.println(numbers);
  }

}
Output:
Before Sorting
5
1
10
3
8
After Sorting
1
3
5
8
10

Java ArrayList example of user-defined objects

We can also use ArrayList to store user-defined objects. The below example shows how we store the Employee class object in an ArrayList. Using this, you can add elements to the ArrayList.

import java.util.ArrayList;
import java.util.Iterator;
class Employee
{
  int empid;
  String empname;
  String empdesignation;
  
  Employee(int empid,String empname,String empdesignation)
  {
    this.empid = empid;
    this.empname = empname;
    this.empdesignation = empdesignation;
  }
}
public class ArrayListObject {

  public static void main(String[] args) {
    //Create Employee class objects
    Employee e1 = new Employee(100,"Rohit","Developer");
    Employee e2 = new Employee(200,"Shyam","Tester");
    Employee e3 = new Employee(205,"Tarun","Trainee");
    
    //Create an arraylist
    ArrayList<Employee> list = new ArrayList<Employee>();
    
    //Add employee objects to the list
    list.add(e1);
    list.add(e2);
    list.add(e3);
    
    //Declare iterator
    Iterator i = list.iterator();
    while(i.hasNext()) {
      //Convert to Employee object to access the elements
      Employee emp = (Employee)i.next();
      System.out.println(emp.empid + " " + emp.empname + " " + emp.empdesignation);
    }
    

  }

}
Output:
100 Rohit Developer
200 Shyam Tester
205 Tarun Trainee

Conclusion

This tutorial discusses in detail about ArrayList and how to initialize an ArrayList in Java, its methods, and how to fetch array elements from the array along with example programs. You might be interested in Java collection interview questions then go and crack the interviews.

Reference

Translate »