ArrayList in java

Let’s learn arraylist in java.

ArrayList in java

  • underlying data structure for arraylist is resizable array.
  • we can add duplicate elements in ArrayList.
  • ArrayList preserves insertion order.
  • Heterogeneous objects can be stored in ArrayList.
  • ArrayList allow null values.
  • ArrayList is part of collection framework.
  • Arraylist implements list interface.
  • ArrayList is a re-sizable array that grows dynamically when elements are added and decreased when elements are removed from collection.
  • For frequent retrieving operation ArrayList is the best. Because elements can be accessed with the same speed.
  • Primitive data types(char, int) cannot be used.
  • We can randomly access using index positions.
  • ArrayList class by default implements Serializable and Cloneable interface.
  • ArrayList class implements RandomAccess interface.
  • Use synchronized keyword to synchronize elements. Since ArrayList is not synchronized.
  • ArrayList is also known as resizable array implementation.

initialize arraylist java

Below are few ways to initialize an arraylist in java.

using add()

Syntax
ArrayList<DataType> al = new ArrayList<DataType>();
al.add("Hello");
al.add("World");
al.add("Java");


using asList()

Syntax:
ArrayList<DataType> obj = new ArrayList<DataType>(
Arrays.asList(obj1, obj2, obj3,..... ));

using List.of() method

List<DataType> obj = new ArrayList<>(
List.of(obj1, obj2, obj3....));


using Collection

List li = new ArrayList<>(collection);

Let’s see an example,

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

public class ArrayListInitialize 
{
   public static void main(String[] args) 
   {
      List<Integer> li = new ArrayList<>(); 
      li.add(2); 
      li.add(4); 
      li.add(6); 
      li.add(8); 
      li.add(10);
      // initialize ArrayList with arraylist li 
      List<Integer> al = new ArrayList<Integer>(li); 
      System.out.println("ArrayList elements: " + al);
   }
}


Output:

ArrayList elements: [2, 4, 6, 8, 10]

Java collection framework provides an architecture to store and manipulate group of objects and it includes interfaces, classes and algorithms.

arraylist in java

In the above figure, green boxes represent interfaces and yellow boxes represent implementation classes.

Here’s arraylist in java example,

import java.util.ArrayList;

public class ArrayListExample 
{
   public static void main(String[] args) 
   {
      ArrayList al = new ArrayList();
      al.add("Raspberry");
      al.add("Vanilla");
      al.add("Raspberry");
      al.add("Apple");
      System.out.println(al);
   }
}



Output:

[Raspberry, Vanilla, Raspberry, Apple]

Creating an ArrayList by adding new elements

import java.util.ArrayList;

public class ArrayListExample 
{
   public static void main(String[] args) 
   {
      ArrayList<String> al = new ArrayList<String>();
      al.add("Raspberry");
      al.add("Vanilla");
      al.add("Raspberry");
      al.add("Apple");
      System.out.println("Given ArrayList elements: " + al);
      // adding new elements
      al.add(2, "Banana");
      System.out.println("By adding new elements: " + al);
   }
}


Output:

Given ArrayList elements: [Raspberry, Vanilla, Raspberry, Apple]
By adding new elements: [Raspberry, Vanilla, Banana, Raspberry, Apple]

ArrayList – creating from another collection

To create from another collection use ArrayList(Collection c) constructor.

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

public class ArrayListCollectionExample 
{
   public static void main(String[] args) 
   {
      List<Integer> evenNumbers = new ArrayList<>();
      evenNumbers.add(2);
      evenNumbers.add(4);
      evenNumbers.add(6);
      evenNumbers.add(8);
      evenNumbers.add(10);
      // create an ArrayList from another collection
      List<Integer> li = new ArrayList<>(evenNumbers);
      List<Integer> oddNumbers = new ArrayList<>();
      oddNumbers.add(1);
      oddNumbers.add(3);
      oddNumbers.add(5);
      oddNumbers.add(7);
      oddNumbers.add(9);
      // add an entire collection to an ArrayList
      li.addAll(oddNumbers);
      System.out.println(li);
   }
}


Output:

[2, 4, 6, 8, 10, 1, 3, 5, 7, 9]

ArrayList isEmpty() method, size() method, get() method and set() method

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

public class ArrayListAccessElements
{
   public static void main(String[] args) 
   {
      List<String> animals = new ArrayList<>();
      // check if it's empty using isEmpty() method
      System.out.println("Animals list empty? : " + animals.isEmpty());
      // adding elements
      animals.add("Giraffe");
      animals.add("Elephant");
      animals.add("Cheetah");
      animals.add("Tiger");
      animals.add("Lion");
      // find size using size() method
      System.out.println("Here are the list of " + animals.size() + " animals");
      System.out.println(animals);
      // retrieve element at given index using get() method
      String fastestAnimal = animals.get(2);
      String tallestAnimal = animals.get(0);
      String lastAnimal = animals.get(animals.size() - 1);
      System.out.println("Fastest animal: " + fastestAnimal);
      System.out.println("Tallest animal: " + tallestAnimal);
      System.out.println("Last animal in the list: " + lastAnimal);
      // modify element at given index using set() method
      animals.set(4, "Deer");
      System.out.println("Modified animals list: " + animals);
   }
}


Output:

Animals list empty? : true
Here are the list of 5 animals
[Giraffe, Elephant, Cheetah, Tiger, Lion]
Fastest animal: Cheetah
Tallest animal: Giraffe
Last animal in the list: Lion
Modified animals list: [Giraffe, Elephant, Cheetah, Tiger, Deer]

Remove elements from ArrayList

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

import java.util.ArrayList;

public class ArrayListRemoveDemo 
{
   public static void main(String[] args) 
   {
      ArrayList<String> animals1 = new ArrayList<String>();  
      animals1.add("Giraffe");
      animals1.add("Elephant");
      animals1.add("Cheetah");
      animals1.add("Tiger");
      animals1.add("Lion");
      System.out.println("Given arraylist: " + animals1);   

      // remove specific element from arraylist  
      animals1.remove("Elephant");  
      System.out.println("remove(object) method: " + animals1);

      // remove element at specific position  
      animals1.remove(1);  
      System.out.println("remove(index) method: " + animals1);

      // create another arraylist animals2
      ArrayList<String> animals2 = new ArrayList<String>();    
      animals2.add("Rhinoceros");
      animals2.add("Hippopotamus");

      // add new elements to arraylist animals1
      animals1.addAll(animals2);  
      System.out.println("New list: " + animals1);

      // remove all new elements from arraylist  
      animals1.removeAll(animals2);  
      System.out.println("removeAll() method: " + animals1);

      // remove elements at specified condition
      // using Lambda expression
      animals1.removeIf(str -> str.contains("Giraffe"));   
      System.out.println("removeIf() method: " + animals1);

      // remove all elements in the list  
      animals1.clear();  
      System.out.println("clear() method: " + animals1);
   }
}


Output:

Given arraylist: [Giraffe, Elephant, Cheetah, Tiger, Lion]
remove(object) method: [Giraffe, Cheetah, Tiger, Lion]
remove(index) method: [Giraffe, Tiger, Lion]
New list: [Giraffe, Tiger, Lion, Rhinoceros, Hippopotamus]
removeAll() method: [Giraffe, Tiger, Lion]
removeIf() method: [Tiger, Lion]
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

Let’s see how to iterate arraylist using forEach java 8, iterator() method, java 8 forEachRemaining() method and 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(tvShow -> {
          System.out.println(tvShow);
      });

      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, first occurrence of an element using indexOf() method and last occurrence of an element using lastIndexOf() method.

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

ArrayList – User defined objects

ArrayList can be of any datatype like Double, String, Integer, ArrayList of HashMap etc,. Let’s see an example,

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

class Student 
{
   private String studentName;
   private int studentAge;

   public Student(String name, int age) 
   {
      this.studentName = name;
      this.studentAge = age;
   }

   public String getName() 
   {
      return studentName;
   }

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

   public int getAge() 
   {
      return studentAge;
   }

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

public class ArrayListUserDefined 
{
   public static void main(String[] args) 
   {
      List<Student> player = new ArrayList<>();
      player.add(new Student("Rohit", 25));
      player.add(new Student("Virat", 24));
      player.add(new Student("Dhoni", 29));
      player.forEach(user -> {
          System.out.println("Player name: " + user.getName() + ", Player age: " + user.getAge());
      });
   }
}


Output:

Player name: Rohit, Player age: 25
Player name: Virat, Player age: 24
Player name: Dhoni, Player age: 29

Sort an ArrayList in java

Here let’s learn to sort an arraylist using ArrayList.sort() method and Collections.sort() method.

// using Collections.sort() method

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

public class ArrayListCollectionsSort 
{
   public static void main(String[] args) 
   {
      List<Integer> num = new ArrayList<>();
      num.add(61);
      num.add(15);
      num.add(28);
      num.add(53);
      num.add(39);
      System.out.println("Before sorting: " + num);
      // sort an ArrayList using Collections.sort()
      Collections.sort(num);
      System.out.println("After sorting: " + num);
   }
}


Output:

Before sorting: [61, 15, 28, 53, 39]
After sorting: [15, 28, 39, 53, 61]

// using ArrayList.sort() method

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

public class ArrayListSortDemo 
{
   public static void main(String[] args) 
   {
      List<String> animals = new ArrayList<>();
      animals.add("Lion");
      animals.add("Jaguar");
      animals.add("MountainGoat");
      animals.add("Deer");
      System.out.println("Animal names: " + animals);
      // using sort() method. pass Comparator to the ArrayList.sort() method.
      animals.sort(new Comparator<String>() 
      {
         @Override
         public int compare(String name1, String name2) 
         {
            return name1.compareTo(name2);
         }
      });
      // using lambda expression
      animals.sort((name1, name2) -> name1.compareTo(name2));
      // concise solution
      animals.sort(Comparator.naturalOrder());
      System.out.println("Sorted animal names: " + animals);
   }
}


Output:

Animal names: [Lion, Jaguar, MountainGoat, Deer]
Sorted animal names: [Deer, Jaguar, Lion, MountainGoat]

ArrayList synchronization in java

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 ArrayListSynchronizeDemo 
{
   public static void main(String[] args) throws InterruptedException
   {
      List<Integer> safeArrayList = Collections.synchronizedList(new ArrayList<>());
      safeArrayList.add(10);
      safeArrayList.add(20);
      safeArrayList.add(30);
      // creating thread pool of size 10
      ExecutorService service = Executors.newFixedThreadPool(10);
      // creating Runnable task that increments each element by one
      Runnable task = () -> {
          incrementArrayList(safeArrayList);
      };

      // submitting task to executor 100 times.
      // tasks will modify ArrayList concurrently
      for(int a = 0; a < 100; a++) 
      {
         service.submit(task);
      }
      service.shutdown();
      service.awaitTermination(60, TimeUnit.SECONDS);
      System.out.println(safeArrayList);
   }

   // incrementing all values by one
   private static void incrementArrayList(List<Integer> safeArrayList) 
   {
      synchronized(safeArrayList) 
      {
         for(int a = 0; a < safeArrayList.size(); a++) 
         {
            Integer value = safeArrayList.get(a);
            safeArrayList.set(a, value + 1);
         }
      }
   }
}


Output:

[110, 120, 130]


Hierarchy of arraylist

arraylist in java

Here is the hierarchy of arraylist class. Arraylist class extends abstractlist. Abstractlist implements list interface.

Also read – hashset in java

And list interface extends collection interface. Collection interface extends iterable interface.


Here methods available in the list interface and collection interface are supported by arraylist class.

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 belongs to java.util package. Arraylist implements list interface. So whatever methods available in list interface are implemented by arraylist.

Constructors in Arraylist,

  • 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.

NOTE:

ArrayList class is not considered as best choice in insertion and deletion of objects.


How to add elements to arraylist in java dynamically?

To add elements to arraylist in java dynamically specify index position in add method. Let’s see an example,

import java.util.ArrayList;

public class ArrayListDemo 
{
   public static void main(String[] args) 
   {
      ArrayList<String> al = new ArrayList<String>();  
      al.add("Snail");
      al.add("Tiger");
      al.add("Lion");
      al.add("Panda");
      al.add("Anteater");
      al.add("Cheetah");
      // print elements
      System.out.println(al);
      // add "Elephant" at the fourth position
      al.add(3, "Elephant");
      // print elements after adding elements dynamically to arraylist
      System.out.println(al);
   }
}


Output:

[Snail, Tiger, Lion, Panda, Anteater, Cheetah]
[Snail, Tiger, Lion, Elephant, Panda, Anteater, Cheetah]


arraylist of objects in java

To sort an arraylist of objects use comparator interface. Here’s the example,

class Employee
{
   private String empName;
   private Integer empAge;

   public Employee(String name, Integer age) 
   {
      this.empName = name;
      this.empAge = age;
   }

   public String getName() 
   {
      return empName;
   }

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

   public Integer getAge() 
   {
      return empAge;
   }

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

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

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

public class ArrayListComparableExample 
{
   public static void main(String[] args) 
   {
      List<Employee> li = new ArrayList<>();
      li.add(new Employee("Sachin", 24));
      li.add(new Employee("Cheteshwar", 25));
      li.add(new Employee("Raina", 26));
      li.add(new Employee("Dravid", 21));
      System.out.println("Employees list : " + li);
      // sorting employees by their age
      li.sort((person1, person2) -> 
      {
         return person1.getAge() - person2.getAge();
      });
      // concise way of writing sorting function
      li.sort(Comparator.comparingInt(Employee :: getAge));
      System.out.println("Sorted employee list by age: " + li);
      // sorting using Collections.sort() method
      Collections.sort(li, Comparator.comparing(Employee :: getName));
      System.out.println("Sorted employee list by name: " + li);
   }
}


Output:

Employees list : [{name=’Sachin’, age=24}, {name=’Cheteshwar’, age=25}, {name=’Raina’, age=26}, {name=’Dravid’, age=21}]
Sorted employee list by age: [{name=’Dravid’, age=21}, {name=’Sachin’, age=24}, {name=’Cheteshwar’, age=25}, {name=’Raina’, age=26}]
Sorted employee list by name: [{name=’Cheteshwar’, age=25}, {name=’Dravid’, age=21}, {name=’Raina’, age=26}, {name=’Sachin’, age=24}]

Reference – Oracle docs