ArrayList in java

Let’s learn arraylist in java.

ArrayList in java

  • java ArrayList allows duplicate elements.
  • Java ArrayList preserves insertion order.
  • java ArrayList is widely used because of its functionality and flexibility. It is designed to hold heterogeneous collections of objects.
  • Java ArrayList can have any number of null values.
  • Java ArrayList is part of collection framework.
  • Java Arraylist implements list interface.
  • Java ArrayList is a re-sizable array that grows dynamically when elements are added and decreased when elements are deleted.
  • For frequent retrieving operation java ArrayList is the best. Because ArrayList elements are stored in consecutive memory locations.
  • ArrayList cannot hold primitive data types such as int, double, char, and long.
  • ArrayList can hold String and wrapper class objects (Double, Integer).
  • ArrayList is index based; we can randomly access elements using index positions.
  • Java ArrayList class implements RandomAccess interface.

Here’s an example on java arraylist.

import java.util.ArrayList;
public class ArrayListExample
{
   public static void main(String[] args)
   {
      int num = 14;
      // declaring ArrayList with initial size num
      ArrayList<Integer> al = new ArrayList<Integer>(num);
      // append new element at the end of list
      for(int a = 1; a <= num; a++)
      {
         al.add(a);
      }
      System.out.println(al);
      // remove element at index 7
      al.remove(7);
      // print ArrayList after deletion
      System.out.println(al);
      // print elements one by one
      for(int a = 0; a < al.size(); a++)
      {
         System.out.print(al.get(a) + " ");
      }
   }
}


Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14]
1 2 3 4 5 6 7 9 10 11 12 13 14


Java Arraylist methods

MethodsDescription
boolean add(Object e)appends the specified element to the end of this list (optional operation).
boolean addAll(Collection C)appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s iterator (optional operation).
void add(int index, Object element)inserts the specified element at the specified position in this list (optional operation).
boolean addAll( int index, Collection C)inserts all of the elements in the specified collection into this list at the specified position (optional operation).
void trimToSize()this method is used to trim the capacity of the instance of the ArrayList to the list’s current size.
boolean remove(Object o)removes the first occurrence of the specified element from this list, if it is present (optional operation).
boolean removeAll(Collection c)removes from this list all of its elements that are contained in the specified collection (optional operation).
boolean retainAll(Collection c)retains only the elements in this list that are contained the specified collection (optional operation).
Object clone()this method is used to return a shallow copy of an ArrayList.
boolean contains(Object o)returns true if this list contains the specified element.
boolean containsAll(Collection c)returns true if this list contains all of the elements of the specified collection.
E get(int index)returns the element at the specified position in this list.
int indexOf(Object o)returns the index of the first occurrence of the specified element in this list, or – 1 if this list does not contain the element.
int lastIndexOf(Object o)returns the index of the last occurrence of the specified element in this list, or – 1 if this list does not contain the element.
void clear()removes all of the elements from this list (optional operation).
boolean isEmpty()returns true if this list contains no elements.
int size()returns the number of elements in this list.
List subList(int fromIndex, int toIndex)returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
Iterator iterator()returns an iterator over the elements in this list in proper sequence.
ListIterator listIterator()returns a list iterator over the elements in this list (in proper sequence).
ListIterator listIterator(int index)returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.
Object[] toArray()returns an array containing all of the elements in this list in proper sequence (from first to last element).
Object[] toArray(Object[] O)is also used to return an array containing all of the elements in this list in the correct order same as the previous method.

Arraylist constructors

  • ArrayList a = new ArrayList() – creates empty ArrayList object with default initial capacity 10.
  • ArrayList a = new ArrayList(Collection c) – this one is parameterized constructor which accepts collection. It will create the arraylist from any collection object.
  • ArrayList a = new ArrayList(int initialCapacity) – this accepts “int” value. it creates empty lists with the specified initial capacity.

Hierarchy of java arraylist

arraylist in java

Example on java ArrayList methods – isEmpty(), size(), get() and set() method

Let’s see example on ArrayList methods namely isEmpty(), size(), get() and set().

java arraylist isEmpty() method example – isEmpty() method returns true if this list contains no elements.

import java.util.ArrayList;
public class ArrayListIsEmptyExample
{
   public static void main(String[] args)
   {
      ArrayList<Integer> al = new ArrayList<Integer>();
      // before checking ArrayList using isEmpty() method
      System.out.println("Is ArrayList empty: " + al.isEmpty());
      al.add(86);
      al.add(25);
      al.add(53);
      al.add(85);
      // after checking ArrayList using isEmpty() method
      System.out.println("Is ArrayList empty: " + al.isEmpty());
      for(Integer a : al)
      {
         System.out.println(a);
      }
   }
}


Output:

Is ArrayList empty: true
Is ArrayList empty: false
86
25
53
85


java arraylist size() method example – size() method returns the number of elements in this list.

import java.util.ArrayList;
public class ArrayListSizeExample
{
   public static void main(String[] args)
   {
      ArrayList<String> al = new ArrayList<>();
      int s = al.size();
      System.out.println("size of ArrayList after creating: " + s);
      al.add("red");
      al.add("blue");
      al.add("green");
      s = al.size();
      System.out.println("size of ArrayList after adding elements: " + s);
      al.clear();
      s = al.size();
      System.out.println("size of ArrayList after clearing elements: " + s);
   }
}


Output:

size of ArrayList after creating: 0
size of ArrayList after adding elements: 3
size of ArrayList after clearing elements: 0


java arraylist get() method example – get() method returns the element at the specified position in this list.

import java.util.ArrayList;
public class ArrayListGetExample
{
   public static void main(String[] args)
   {
      ArrayList<String> al = new ArrayList<String>();
      al.add("lion");
      al.add("tiger");
      al.add("deer");
      al.add("cheetah");
      al.add("elephant");
      al.add("fox");
      al.add("hyenas");
      al.add("jackal");
      System.out.println("Get second element of ArrayList: " + al.get(1));
      System.out.println("Get third element of ArrayList: " + al.get(2));
      System.out.println("Get fifth element of ArrayList: " + al.get(4));
      System.out.println("Get sixth element of ArrayList: " + al.get(5));
   }
}


Output:

Get second element of ArrayList: tiger
Get third element of ArrayList: deer
Get fifth element of ArrayList: elephant
Get sixth element of ArrayList: fox


java arraylist set() method example – set() method replaces the element at the specified position in this list with the specified element.

import java.util.ArrayList;
public class ArrayListSetExample
{
   public static void main(String[] args)
   {
      ArrayList<Integer> al = new ArrayList<Integer>();
      al.add(2);
      al.add(4);
      al.add(6);
      al.add(8);
      al.add(10);
      al.add(12);
      al.add(14);
      System.out.println("ArrayList before using set() method: " + al);
      // update second element
      al.set(1, 58);
      // update third element
      al.set(2, 85);
      // update fourth element
      al.set(3, 39);
      // update fifth element
      al.set(4, 43);
      // update sixth element
      al.set(5, 93);
      System.out.println("ArrayList after using set() method: " + al);
   }
}


Output:

ArrayList before using set() method: [2, 4, 6, 8, 10, 12, 14]
ArrayList after using set() method: [2, 58, 85, 39, 43, 93, 14]


ArrayList example – Remove elements

To remove elements from an arraylist use following methods: remove(int index), remove(Object o), removeAll(), removeIf() and clear() method.

Java ArrayList remove(int index) method example – this method removes the element at the specified position in this list.

Shifts any subsequent elements to the left (subtracts one from their indices).

import java.util.ArrayList;
public class ArrayListRemoveIndexExample
{
   public static void main(String[] args)
   {
      ArrayList<String> al = new ArrayList<String>();
      al.add("green");
      al.add("blue");
      al.add("red");
      al.add("orange");
      al.add("yellow");
      al.add("pink");
      System.out.println("ArrayList before remove(int index) method: ");
      for(String str : al)
      {
         System.out.println(str);
      }
      // remove second element
      al.remove(1);
      // remove third element from remaining list
      al.remove(2);
      // remove fourth element from remaining list
      al.remove(3);
      System.out.println("ArrayList After remove(int index) method: ");
      for(String str1 : al)
      {
         System.out.println(str1);
      }
   }
}


Output:

ArrayList before remove(int index) method:
green
blue
red
orange
yellow
pink
ArrayList After remove(int index) method:
green
red
yellow


Java ArrayList remove(Object o) method example – this method returns true if this list contained the specified element.

import java.util.ArrayList;
public class ArrayListRemoveObjectExample
{
   public static void main(String[] args)
   {
      ArrayList<String> al = new ArrayList<String>();
      al.add("vijay");
      al.add("virat");
      al.add("ajay");
      al.add("rohit");
      al.add("sundar");
      al.add("bharat");
      System.out.println("ArrayList before remove(Object o) method: ");
      for(String str : al)
      {
         System.out.println(str);
      }
      // remove element ajay
      al.remove("ajay");
      // remove element rohit
      al.remove("rohit");
      // remove element bharat
      al.remove("bharat");
      // prakash element is not present
      // hence return false
      boolean bool = al.remove("prakash");
      System.out.println("Is element prakash removed?: " + bool);
      System.out.println("ArrayList After remove(Object o) method: ");
      for(String str1 : al)
      {
         System.out.println(str1);
      }
   }
}


Output:

ArrayList before remove(Object o) method:
vijay
virat
ajay
rohit
sundar
bharat
Is element prakash removed?: false
ArrayList After remove(Object o) method:
vijay
virat
sundar


ArrayList removeAll() method java example – removes from this list all of its elements that are contained in the specified collection.

import java.util.ArrayList;
public class ArrayListRemoveAllExample
{
   public static void main(String[] args)
   {
      try
      {
         ArrayList<Integer> al1 = new ArrayList<Integer>();
         al1.add(2);
         al1.add(4);
         al1.add(6);
         al1.add(8);
         al1.add(10);
         System.out.println("ArrayList before using removeAll() method: " + al1);
         // create another ArrayList
         ArrayList<Integer> al2 = new ArrayList<Integer>();
         al2.add(2);
         al2.add(4);
         al2.add(6);
         // print al2
         System.out.println("Elements to be removed: " + al2);
         // remove elements from ArrayList using removeAll() method
         al1.removeAll(al2);
         // print al1
         System.out.println("ArrayList after using removeAll() method: " + al1);
      }
      catch(NullPointerException ex)
      {
         System.out.println("Exception: " + ex);
      }
   }
}


Output:

ArrayList before using removeAll() method: [2, 4, 6, 8, 10]
Elements to be removed: [2, 4, 6]
ArrayList after using removeAll() method: [8, 10]


ArrayList removeIf() method java example – this method removes all of the elements of this collection that satisfy the given predicate.

import java.util.ArrayList;
public class ArrayListRemoveIfExample
{
   public static void main(String[] args)
   {
      ArrayList<Integer> al = new ArrayList<Integer>();
      al.add(15);
      al.add(8);
      al.add(58);
      al.add(19);
      // remove numbers divisible by 2
      al.removeIf(n -> (n % 2 == 0));
      // print list
      for(int a : al)
      {
         System.out.println(a);
      }
   }
}


Output:

15
19


ArrayList clear() method java example – this method removes all of the elements from this list.

import java.util.ArrayList;
public class ArrayListClearExample
{
   public static void main(String[] args)
   {
      ArrayList al = new ArrayList(4);
      al.add(9);
      al.add(3);
      al.add(5);
      al.add(1);
      System.out.println("ArrayList before clear() method: " + al);
      al.clear();
      System.out.println("ArrayList after clear() method: " + al);
   }
}


Output:

ArrayList before clear() method: [9, 3, 5, 1]
ArrayList after clear() method: []


ArrayList iteratorRemove() method with example

import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListIteratorRemoveDemo 
{
   public static void main(String[] args) 
   {
      ArrayList<String> al = new ArrayList<String>();
      al.add("Giraffe");
      al.add("Elephant");
      al.add("Cheetah");
      al.add("Tiger");
      al.add("Lion");
      System.out.println("Given ArrayList elements: ");
      for(String strAnimal : al) 
      {
         System.out.println(strAnimal);
      }
      Iterator iterate = al.iterator();
      String str = "";
      while(iterate.hasNext()) 
      {
         str = (String)iterate.next();
         if(str.equals("Tiger")) 
         {
            iterate.remove();
            System.out.println("\nElement Tiger removed");
            break;
         }
      }
      System.out.println("\nUpdated ArrayList elements: ");
      for(String a: al) 
      {
         System.out.println(a); 
      }
   }
}


Output:

Given ArrayList elements:
Giraffe
Elephant
Cheetah
Tiger
Lion

Element Tiger removed

Updated ArrayList elements:
Giraffe
Elephant
Cheetah
Lion


Java Iterate ArrayList or loop through ArrayList

Let’s see how to iterate or loop through ArrayList using forEach java 8, iterator() method, java 8 forEachRemaining() method, iterator(), listIterator(), for-each loop and for loop.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class ArrayListIterateDemo 
{
   public static void main(String[] args) 
   {
      ArrayList<String> birds = new ArrayList<String>();
      birds.add("Sparrow");
      birds.add("Pigeon");
      birds.add("Peacock");
      birds.add("Eagle");
      System.out.println("Java 8 forEach and lambda expression: ");
      birds.forEach(bird -> {
          System.out.println(bird);
      });
      System.out.println("\niterator() method: ");
      Iterator<String> str = birds.iterator();
      while(str.hasNext())
      {
         String b = str.next();
         System.out.println(b);
      }
      System.out.println("\niterator() and Java 8 forEachRemaining() method: ");
      str = birds.iterator();
      str.forEachRemaining(n -> {
          System.out.println(n);
      });
      System.out.println("\nIterate using a listIterator(): ");
      // starting from the end of the list and traverse backwards
      ListIterator<String> liIterator = birds.listIterator(birds.size());
      while(liIterator.hasPrevious()) 
      {
         String strBirds = liIterator.previous();
         System.out.println(strBirds);
      }
      System.out.println("\nfor-each loop: ");
      for(String s: birds) 
      {
         System.out.println(s);
      }
      System.out.println("\nfor loop with index: ");
      for(int a = 0; a < birds.size(); a++) 
      {
         System.out.println(birds.get(a));
      }
   }
}


Output:

Java 8 forEach and lambda expression:
Sparrow
Pigeon
Peacock
Eagle

iterator() method:
Sparrow
Pigeon
Peacock
Eagle

iterator() and Java 8 forEachRemaining() method:
Sparrow
Pigeon
Peacock
Eagle

Iterate using a listIterator():
Eagle
Peacock
Pigeon
Sparrow

for-each loop:
Sparrow
Pigeon
Peacock
Eagle

for loop with index:
Sparrow
Pigeon
Peacock
Eagle


Search elements in an ArrayList

In the below example let’s learn how to search elements using ArrayList contains() method, indexOf() method to search first occurrence of an element and lastIndexOf() method to search last occurrence of an element.

import java.util.ArrayList;
import java.util.List;
public class ArrayListSearchElements 
{
   public static void main(String[] args) 
   {
      List<String> players = new ArrayList<>();
      players.add("Ishant");
      players.add("Ravindra");
      players.add("Virat");
      players.add("Ajinkya");
      players.add("Rohit");
      players.add("Bhuvaneshwar");
      players.add("Dhoni");
      // check if ArrayList contains given element
      System.out.println("Does players arraylist contain \"Virat\"? : " + players.contains("Virat"));
      // find index of first occurrence of an element
      System.out.println("indexOf \"Ajinkya\": " + players.indexOf("Ajinkya"));
      System.out.println("indexOf \"Vijay\": " + players.indexOf("Vijay"));
      // find index of the last occurrence of an element
      System.out.println("lastIndexOf \"Ishant\" : " + players.lastIndexOf("Ishant"));
      System.out.println("lastIndexOf \"Vinod\" : " + players.lastIndexOf("Vinod"));
   }
}


Output:

Does players arraylist contain “Virat”? : true
indexOf “Ajinkya”: 3
indexOf “Vijay”: -1
lastIndexOf “Ishant” : 0
lastIndexOf “Vinod” : -1


Sorting an ArrayList

To sort an java arraylist there is sort() method of Collections class of java.util package which sorts alphabets and numerals.

Let’s see an example to sort an ArrayList of strings.

import java.util.ArrayList;
import java.util.Collections;
public class ArrayListStrings
{
   public static void main(String[] args)
   {
      ArrayList<String> al = new ArrayList<String>();
      al.add("Banana");
      al.add("Pineapple");
      al.add("Jackfruit");
      al.add("Apple");
      Collections.sort(al);
      for(String str : al)
      {
         System.out.println(str);
      }
   }
}


Output:

Apple
Banana
Jackfruit
Pineapple


Let’s see an example to sort an ArrayList of Integers.

import java.util.ArrayList;
import java.util.Collections;
public class ArrayListIntegers
{
   public static void main(String[] args)
   {
      ArrayList<Integer> al = new ArrayList<Integer>();
      al.add(86);
      al.add(22);
      al.add(61);
      al.add(83);
      al.add(59);
      al.add(39);
      Collections.sort(al);
      for(int num : al)
      {
         System.out.println(num);
      }
   }
}


Output:

22
39
59
61
83
86

Reference – Oracle docs