ArrayList Class In Java

ArrayList Class In Java: ArrayList is a collection class that implements the List interface, and it is based on the Array Data Structure. Most programs use ArrayList over Array Because of ArrayList’s Functionality and flexibility over Array.

Essential Points About ArrayList In Java

  • ArrayList is a re-sizeable array, so it is also called a dynamic array. If you add new elements, its size automatically increases, and when you delete the elements, the size automatically shrank.
  • The ArrayList stores the elements in an array, so you can retrieve the elements by using the index.
  • It allows duplicate and null values.
  • The ArrayList elements are stored inside the ArrayList collection as per the insertion order.
  • You can not create an ArrayList of primitive data types like int, char, etc. But we can create an ArrayList of Wrapper classes like Integer, Character, Boolean, etc.
  • Java ArrayList is not synchronized or thread-safe, so the final result is non-deterministic if multiple threads act on ArrayList. If you want your ArrayList to provide an expected result, then you need to set the ArrayList as synchronized explicitly.

Why is ArrayList better than an Array?

One of the main limitations of an array is that it has a fixed length, So if you add the mentioned number of elements to it, you can not add more elements. Similarly, if you remove a few elements from an array, the size does not shrink.

An ArrayList is growable and will extend its size after adding new elements. Similarly, if you remove any elements from an ArrayList, it shrinks its size. Apart from this, ArrayList also provides us with some predefined methods which help us to increase our productivity.

How to create an ArrayList?

We can create an ArrayList by using simple statements like we are creating an object. Check the syntax below for creating an ArrayList.

ArrayList<String> alist=new ArrayList<String>();

The above syntax helps to create an ArrayList of name list, and as we have mentioned “String”, this collection ArrayList will allow us to add string type elements into it. Similarly, if you want to add int-type elements into it, then the syntax for that is

ArrayList<Integer> list=new ArrayList<Integer>();

Java ArrayList Class Constructors

There are three types of constructors are present in the ArrayList class:

  • Public ArrayList(): This type of constructor is used by most programmers. This constructor will return an empty list with an initializing size of 10.
  • ArrayList(int capacity): This constructor is used to build an ArrayList with the mentioned initial capacity.
  • ArrayList(Collection c): This constructor is used to build an ArrayList initialized with the elements from collection c.

Different Methods Of ArrayList

The ArrayList consists of so many methods, but let’s discuss some of the important methods that are used by programmers commonly:

  • add( Object o)
  • add(int index, Object o):
  • remove(Object o):
  • remove(int index):
  • set(int index, Object o):
  • int indexOf(Object o):
  • Object get(int index):
  • int size():
  • boolean contains(Object o):
  • clear():

How to add elements to an ArrayList? [Program]
How to remove elements from ArrayList? [Program]
Iterating ArrayList [ Program]

Write A Program For Different Operation ArrayList In Java?

package com.java.Softwaretestingblog;
import java.util.ArrayList;
public class MyBasicArrayList {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      ArrayList<String> al = new ArrayList<String>();
      //add elements to the ArrayList
      al.add("JAVA");
      al.add("C++");
      al.add("PERL");
      al.add("PHP");
      System.out.println(al);
      //get elements by index
      System.out.println("Element at index 1: "+al.get(1));
      System.out.println("Does list contains JAVA? "+al.contains("JAVA"));
      //add elements at a specific index
      al.add(2,"PLAY");
      System.out.println(al);
      System.out.println("Is arraylist empty? "+al.isEmpty());
      System.out.println("Index of PERL is "+al.indexOf("PERL"));
      System.out.println("Size of the arraylist is: "+al.size());
   }
}

Output:

[JAVA, C++, PERL, PHP]
Element at index 1: C++
Does list contains JAVA? true
[JAVA, C++, PLAY, PERL, PHP]
Is arraylist empty? false
Index of PERL is 3
Size of the arraylist is: 5

Write a Program Adding New Element ArrayList In Java With Example?

package com.java.Softwaretestingblog;
import java.util.ArrayList;
import java.util.List;
public class MyArrayListNewCollection {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      ArrayList<String> arrl = new ArrayList<String>();
      //adding elements to the end
      arrl.add("First");
      arrl.add("Second");
      arrl.add("Third");
      arrl.add("Random");
      System.out.println("Actual ArrayList:"+arrl);
      List<String> list = new ArrayList<String>();
      list.add("one");
      list.add("two");
      arrl.addAll(list);
      System.out.println("After Copy: "+arrl);
   }
}

Output:

Actual ArrayList:[First, Second, Third, Random]
After Copy: [First, Second, Third, Random, one, two]

Write a Program For Access Elements Using ArrayList Iterator In Java?

package com.java.Softwaretestingblog;
import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListIterator {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      ArrayList<String> arrl = new ArrayList<String>();
        //adding elements to the end
        arrl.add("First");
        arrl.add("Second");
        arrl.add("Third");
        arrl.add("Random");
        Iterator<String> itr = arrl.iterator();
        while(itr.hasNext())
        {
            System.out.println(itr.next());
        }
   }
}

Output:

First
Second
Third
Random

Write a Program to Reverse Array List Elements In Java With Example.

package com.java.Softwaretestingblog;
import java.util.ArrayList;
import java.util.Collections;
public class MyArrayListReverse {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      ArrayList<String> list = new ArrayList<String>();
      list.add("Java");
      list.add("Cric");
      list.add("Play");
      list.add("Watch");
      list.add("Glass");
      Collections.reverse(list);
      System.out.println("Results after reverse operation:");
      for(String str: list)
      {
         System.out.println(str);
      }
   }
}

Output:

Results after reverse operation:
Glass
Watch
Play
Cric
Java

Clear ArrayList Java Program: Write a Program For Clear ArrayList Values In Java With Example?

package com.java.Softwaretestingblog;

import java.util.ArrayList;
public class ClearMyArrayList {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      ArrayList<String> arrl = new ArrayList<String>();
      //adding elements to the end
      arrl.add("First");
      arrl.add("Second");
      arrl.add("Third");
      arrl.add("Random");
      System.out.println("Actual ArrayList:"+arrl);
      arrl.clear();
      System.out.println("After clear ArrayList:"+arrl);
   }
}

Output:

Actual ArrayList:[First, Second, Third, Random]
After clear ArrayList:[]

Retrieve ArrayList Elements In Java: Write a Program to Retrieve ArrayList Elements In Java with Example?

package com.java.Softwaretestingblog;
import java.util.ArrayList;
public class RetrieveElementsfromArrayList {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      ArrayList<String> arrl = new ArrayList<String>();
      arrl.add("First");
      arrl.add("Second");
      arrl.add("Third");
      arrl.add("Random");
      System.out.println("Actual ArrayList:"+arrl);
      String[] strArr = new String[arrl.size()];
      arrl.toArray(strArr);
      System.out.println("Created Array content:");
      for(String str:strArr)
      {
         System.out.println(str);
      }
   }
}

Output:

Actual ArrayList:[First, Second, Third, Random]
Created Array content:
First
Second
Third
Random

Reverse Elements Of ArrayList In Java Collection Program: Write a program to reverse elements of array list in Java.

package com.java.Softwaretestingblog;
import java.util.ArrayList;
import java.util.List;

public class ReverseElementsArrayList {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      List<Integer> list = new ArrayList<Integer>();
      list.add(1);
      list.add(2);
      list.add(1);
      List<Integer> list1 = new ArrayList<Integer>();
      //System.out.println(list1);
      for(int i=list.size()-1;i>=0;i--)
      {
         //Integer k=list.get(i);
         for(int j=0;j<=list.size()-1;j++)
         {
            //Integer l=list.get(j);
            //System.out.println(k);
            //System.out.println(l);
            if(list.get(i).equals(list.get(j)))
            {
               list1.add(list.get(j));
               break;
            }
         }


      }
      System.out.println(list);
      System.out.println(list1);
      if(list.equals(list1))
      {
         System.out.println("Palendrome");
      }
      else
         System.out.println("not Palendrome");

   }
}

Output:

Elements in forward directiton
23
98
29
71
5
Elements in backward directiton
5
71
29
98
23

Swap ArrayList Elements Java Program: Write a Program to Swap ArrayList Elements In Java With Example?

package com.java.Softwaretestingblog;
import java.util.ArrayList;
import java.util.Collections;
public class MyArrayListSwap {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      ArrayList<String> list = new ArrayList<String>();
      list.add("Java");
      list.add("Cric");
      list.add("Play");
      list.add("Watch");
      list.add("Glass");
      list.add("Movie");
      list.add("Girl");

      Collections.swap(list, 2, 5);
      System.out.println("Results after swap operation:");
      for(String str: list){
         System.out.println(str);
      }
   }
}

Output:

Results after swap operation:
Java
Cric
Movie
Watch
Glass
Play
Girl

Write a Program to Verify Between List & ArrayList elements in Java.

package com.java.Softwaretestingblog;
import java.util.ArrayList;
import java.util.List;
public class MyElementCheck {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      ArrayList<String> arrl = new ArrayList<String>();
      arrl.add("First");
      arrl.add("Second");
      arrl.add("Third");
      arrl.add("Random");
      List<String> list = new ArrayList<String>();
      list.add("Second");
      list.add("Random");
      System.out.println("Does ArrayList contains all list elements?: "
            +arrl.containsAll(list));
      list.add("one");
      System.out.println("Does ArrayList contains all list elements?: "
            +arrl.containsAll(list));
   }
}

Output:

Java
Unix
Oracle
C++
Perl

How do you remove duplicate numbers without using Java Collection?

package com.softwaretestingblog.programs;
import java.util.ArrayList;
public class RemoveDuplicateNumberWithOutCollection {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      ArrayList<Object> al = new ArrayList<Object>();
      al.add("SoftwareTestingBlog");
      al.add('a');
      al.add('b');
      al.add('a');
      al.add("SoftwareTestingBlog");
      al.add(10.3);
      al.add('c');
      al.add(14);
      al.add("SoftwareTestingBlog");
      al.add(12);
      System.out.println("Before Remove Duplicate elements:"+al);
      for(int i=0;i<al.size();i++){

         for(int j=i+1;j<al.size();j++){
            if(al.get(i).equals(al.get(j))){
               al.remove(j);
               j--;
            }
         }
      }
      System.out.println("After Removing duplicate elements:"+al);
   }
}

Output:

Before Remove Duplicate elements:[SoftwareTestingBlog, a, b, a, SoftwareTestingBlog, 10.3, c, 14, SoftwareTestingBlog, 12]
After Removing duplicate elements:[SoftwareTestingBlog, a, b, 10.3, c, 14, 12]

Avatar for Softwaretestingo Editorial Board

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment