Java Collections

ArrayList Class in Java Collection Framework

The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed.

Standard Java arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold.

Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.

ArrayList class

  • ArrayList class extends AbstractList class and implements the List interface.
  • ArrayList supports dynamic array that can grow as needed. ArrayList has three constructors.
//constructor builds an empty array list
ArrayList()
//The following constructor builds an array list that is initialized with the elements of the collection c.
ArrayList( Collection C )
/*The following constructor builds an array list that has the specified initial capacity. The capacity is the size of the underlying array that is used to store the elements.

The capacity grows automatically as elements are added to an array list.*/
ArrayList( int capacity )
  • ArrayLists are created with an initial size, when this size is exceeded, it gets enlarged automatically.
  • It can coontain Duplicate elements and maintains the insertion order.
  • ArrayLists are not synchronized.

Methods in the ArrayList Class:

Apart from the methods inherited from its parent classes, ArrayList defines following methods:
SN Methods with Description
1 void add(int index, Object element)
Inserts the specified element at the specified position index in this list. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index > size()).
2 boolean add(Object o) 
Appends the specified element to the end of this list.
3 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. Throws NullPointerException if the specified collection is null.
4 boolean addAll(int index, Collection c) 
Inserts all of the elements in the specified collection into this list, starting at the specified position. Throws NullPointerException if the specified collection is null.
5 void clear() 
Removes all of the elements from this list.
6 Object clone() 
Returns a shallow copy of this ArrayList.
7 boolean contains(Object o) 
Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
8 void ensureCapacity(int minCapacity) 
Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
9 Object get(int index) 
Returns the element at the specified position in this list. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()).
10 int indexOf(Object o) 
Returns the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.
11 int lastIndexOf(Object o)
Returns the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
12 Object remove(int index) 
Removes the element at the specified position in this list. Throws IndexOutOfBoundsException if index out of range (index < 0 || index >= size()).
13 protected void removeRange(int fromIndex, int toIndex) 
Removes from this List all of the elements whose index is between fromIndex, inclusive and toIndex, exclusive.
14 Object set(int index, Object element) 
Replaces the element at the specified position in this list with the specified element. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()).
15 int size() 
Returns the number of elements in this list.
16 Object[] toArray() 
Returns an array containing all of the elements in this list in the correct order. Throws NullPointerException if the specified array is null.
17 Object[] toArray(Object[] a) 
Returns an array containing all of the elements in this list in the correct order; the runtime type of the returned array is that of the specified array.
18 void trimToSize() 
Trims the capacity of this ArrayList instance to be the list’s current size.

Example of ArrayList:

import java.util.*;

public class ArrayListDemo {
   public static void main(String args[]) {
      // create an array list
      ArrayList list = new ArrayList();
      System.out.println("Initial size of list: " + list.size());

      // add elements to the array list
      list.add("Dinesh");
      list.add("Sweety");
      list.add("Adesh");
      list.add("Vinesh");
      list.add("Mom");
      list.add("DAD");
      
      System.out.println("Size of list after additions: " + list.size());

      // display the array list
      System.out.println("Contents of list: " + list);
     
       System.out.println("Iterating list");
       Iterator itr = list.iterator();
       while(itr.hasNext()){
           System.out.println(itr.next());
       }
   }
}

output:

Two ways to iterate the elements of collection:

  1. By Iterator interface.
  2. By for-each loop.

Iterating the elements of Collection by for-each loop:

import java.util.*;

public class ArrayListDemo {
   public static void main(String args[]) {
      // create an array list
      ArrayList list = new ArrayList();
      
      // add elements to the array list
      list.add("Dinesh");
      list.add("Sweety");
      list.add("Adesh");
      list.add("Vinesh");
      list.add("Mom");
      list.add("DAD");
      System.out.println("Iterating list using for each loop");
      for(Object obj : list){
           System.out.println(obj);
      }
   }
}

output:

Storing User-Defined classes:
In the above example we are storing only string object in ArrayList collection. But You can store any type of object, including object of class that you create in Collection classes.
Example of storing User-Defined object

Employee class

class Employee
{
    String firstName;
    String lastName;
    String phone;

    public Employee(String firstName,String lastName,String phone) 
    {
        this.firstName = firstName ;
        this.lastName = lastName;
        this.phone = phone;
    }
    
    public String toString()
    {
        return firstName +" "+lastName +" ("+phone +") ";
    }
}

Storing Employee class

public class EmployeeListDemo
{
    
   public static void main(String[] args) 
   {
       Employee e1 = new Employee("Dinesh", "Rajput","999100091");
       Employee e2 = new Employee("Sandeep", "Sharma","998392819");
       Employee e3 = new Employee("Vinesh", "Kohli","998131319");
       
      ArrayList al = new ArrayList(); 
      al.add(e1);
      al.add(e2);
      al.add(e3);
      System.out.println(al);
   }
    
}

output:

Example of addAll(Collection c) method:

import java.util.*;
class SimpleListDemo{
 public static void main(String args[]){
 
  ArrayList al = new ArrayList();
  al.add("Dinesh");
  al.add("Anamika");
  al.add("Sweety");
  
  ArrayList al2 = new ArrayList();
  al2.add("Adesh");
  al2.add("Vinesh");
  
  al.addAll(al2);  

  Iterator itr=al.iterator();
  while(itr.hasNext()){
   System.out.println(itr.next());
  }
 }
}

output:

Example of removeAll() method:

import java.util.*;
class SimpleListDemo{
 public static void main(String args[]){
 
  ArrayList al = new ArrayList();
  al.add("Dinesh");
  al.add("Anamika");
  al.add("Sweety");
  
  ArrayList al2 = new ArrayList();
  al2.add("Anamika");
  al2.add("Vinesh");

  al.removeAll(al2);  

  Iterator itr=al.iterator();
  while(itr.hasNext()){
   System.out.println(itr.next());
  }
 }
}

output:

Example of retainAll() method:

import java.util.*;
class SimpleListDemo{
 public static void main(String args[]){
 
  ArrayList al = new ArrayList();
  al.add("Dinesh");
  al.add("Anamika");
  al.add("Sweety");
  
  ArrayList al2 = new ArrayList();
  al2.add("Anamika");
  al2.add("Vinesh");
  System.out.println("iterating the elements after retaining the elements of al2...");
  al.retainAll(al2);  

  Iterator itr=al.iterator();
  while(itr.hasNext()){
   System.out.println(itr.next());
  }
 }
}

output:

 

<<Previous <<   || Index ||   >>Next >>

 

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago