Java/J2EE and SOA (16 Blogs) Become a Certified Professional

Java ArrayList: A Complete Guide for Beginners

1.2K Views

Become a Certified Professional

We all know that arrays are an important structure in Java which can be used to store static data. But, what if your data needs to be stored dynamically? In order to do this, Java offers a special collection framework called Java ArrayList that is specifically meant to store dynamic data. In this article, I will introduce you to this advanced class of arrays and show you how they differ from their static counterparts. Here are the topics that will be covered in this tutorial:

Introduction to ArrayList

ArrayList is the implementation of List Interface where the elements can be dynamically added or removed from the list. Also, the size of the list is increased dynamically if the elements are added more than the initial size. Though it may be slower than standard arrays, it can be helpful in programs where lots of manipulation in the array is needed.

Vector - Java Collections - Edureka

So how do you declare an ArrayList?

It’s very simple. Declaring an ArrayList is as follows.
Declaration:  ArrayList al= new ArrayList();
al ->is a reference to an ArrayList that holds references to objects.

 

What is the use of ArrayList?

  • ArrayList in Java is used to store a dynamically sized collection of elements.
  • ArrayList is initialized by a size. However, the size can increase if the collection grows, and shrunk if objects are removed from the collection.
  • Java ArrayList allows us to randomly access the list.

Java ArrayList Tutorial | Java ArrayList Examples | Edureka


Hierarchy of ArrayList in the Collections Framework

ArrayList uses a dynamic array for storing the elements. It inherits AbstractList class and implements List interface. The List interface extends Collection and Iterable interfaces in hierarchical order.

Hirerarchy of ArrayList-Java ArrayList-Edureka

  • Iterable: It is one of the root Interface of Java Collections Class. The interface extends Collection Iterable so all subtypes of Collections also implement the interface Iterable.
  • Collection: The java.util.Collections class consists exclusively of static methods that operate on or return collections.
  • List: Java.util.List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. List Interface is implemented by ArrayList, LinkedList, Vector and Stack classes.
  • Abstract List: AbstractList class is an abstract class which extends the class AbstractCollection and implements the interface List.
  • ArrayList: ArrayList is the implementation of List Interface where the elements can be dynamically added or removed from the list.

Subscribe to our YouTube channel to get new updates..!

Constructors in ArrayList

ConstructorDescription
  1. ArrayList()         Used to build an empty array list
  2. ArrayList(Collection c)         Builds an array list that is initialized with the elements of collection c
  3. ArrayList(int capacity)         Used to build an array list that has the specified initial capacity

Example Illustrating the use of Constructors:

public class Constructors {
public static void main(String args[]){ 
ArrayList a = new ArrayList(); // Creating a new ArrayList

  int counter = 0;
  for(String: a ) {
    counter++;
 }
System.out.println("No arguments: (can't obtain)" + counter);
ArrayList b = new ArrayList(41); // Initializing capacity to ArrayList
counter = 0;
for(String: b ) {
 counter++;
}

System.out.println("Argument with capacity: (can't obtain)" + counter);
System.out.println();
String sArray[] = {"Bangalore", "Delhi", "Mumbai", "Pune", "Kerala", "Gujurat"};
List list = Arrays.asList(sArray);
ArrayList c = new ArrayList(list);
c.add("Dharwad");
for(String s: c) {
System.out.println("ArrayList c element:" + s);
}
System.out.println(c);
}
}

 

    
Get Certified With Industry Level Projects & Fast Track Your Career

Java ArrayList Methods

  • void add(int index, Object element):  This method is used to insert a specific element at a specific position index in a list.
    For Example:

package Edureka; 
import java.util.*; 
public class Arraylist { 
public static void main(String args[]) 
{ 
ArrayList al= new ArrayList();
al.add("Edureka); 
al.add("Java"); // Adding elements to ArrayList
al.add("Arrays");
 System.out.println("Size of arraylist:" +al.size());
 System.out.println("Contents of al:" +al); 
} 
}

In the above code, It adds the elements to the created ArrayList.

  • Object remove(int index):
    This method removes the first occurrence of the specified element from this list if it is present. If the list does not contain the element, it is unchanged.
    For Example:
public class Arraylist {
public static void main(String args[])
{
ArrayList al= new ArrayList();
al.add("Edureka");
al.add("Java");
al.add("Arrays");
System.out.println("Size of arraylist:" +al.size());
System.out.println("Contents of al:" +al);
al.remove("Java"); // Removes Java element from the list
System.out.println("Contents of al:" +al);
}
}
  • Int size():
    It returns the number of elements in this list i.e the size of the list
    For Example:

    public class Arraylist {
    public static void main(String args[])
    {
    ArrayList al= new ArrayList();
    al.add("Edureka");
    al.add("Java");
    al.add("Arrays");
    int asize = al.size(); // returns the size of the array
    System.out.println("Size of the array is:" +asize);
    }
    }
    
  • Object clone():
    This method returns a shallow copy of this ArrayList. i.e. it clones the entire ArrayList.
    For Example:

    public class Arraylist {
    public static void main(String args[])
    {
    ArrayList al= new ArrayList();
    Object cloneList; // Creating an object of clone
    al.add("Edureka");
    al.add("Java");
    al.add("Arrays");
    System.out.println("Contents of ArrayList al:" +al);
    cloneList= al.clone(); //Clones the entire ArrayList
    System.out.println("Elements in the cloned list are:");
    System.out.println(cloneList);
    }
    }
    
  • Object[] to Array():

    It is used to return an array containing all of the elements in the list in correct order.
    For Example:

    public class Arraylist {
    public static void main(String args[])
    {
    ArrayList al= new ArrayList();
    al.add("Edureka");
    al.add("Java");
    al.add("Arrays");
    System.out.println("Contents of ArrayList al:" +al);
    Object[] objArray = al.toArray();
    System.out.println("Elements in the array list are:");
    for(int i=0; i<=objArray.length; i++)
    System.out.println(objArray[i]);
    }
    }
    

     

  • void clear():
    This method is used to remove all the elements from any list.
    For Example:

    public class Arraylist {
    public static void main(String args[])
    {
    ArrayList al= new ArrayList();
    al.add("Edureka");
    al.add("Java");
    al.add("Arrays");
    System.out.println("Contents of ArrayList al:" +al);
    al.clear(); // Removes element from Array
    System.out.println("Arraylist after clear:" +al);
    }
    }
    
  • int IndexOf(Object O): 
    This method returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
    For Example:

    public class IndexOf {
    public static void main(String args[])
    {
    ArrayList Integer al = new ArrayList Integer(9);
    al.add(2);
    al.add(4);
    al.add(5);
    al.add(9);
    System.out.print("The initial values in ArrayList are :");
    for (Integer value : al) {
    System.out.print(value);
    System.out.print(" ");
    }
    int pos =al.indexOf(5)// using indexOf() to find index of 5
    System.out.println("\nThe element 5 is at index :" + pos);
    }
    }
    
  • void trimToSize():
    The trimToSize() method in Java trims the capacity of an ArrayList instance to be the list’s current size. This method is used to trim an ArrayList instance to the number of elements it contains.

    For Example:

    public class TrimtoSize {
    public static void main(String args[]){
    ArrayListInteger al = new ArrayListInteger(9);
    al.add(2);
    al.add(4);
    al.add(5);
    al.add(7);
    al.trimToSize();
    System.out.println("The List elements are:");
    for (Integer number : al) {
    System.out.println("Number =": + number);
    }
    }
    }
    

Difference between ArrayList and Arrays:

ArrayListArrays
  It is of variable-length because it is dynamic in size    It is of fixed length.
  Can add different object and data into the list    Supports only primitive data-type
  Allows addition of duplicate elements    Does not support a duplicate addition
  Can traverse in both forward and backward direction    Can traverse only in a forward direction
  Size can be modified dynamically    Size cannot be modified dynamically

 

This brings us to the end of our blog on Java ArrayList. I hope this blog was informative and added value to your knowledge in Java.

Wish to learn Java from Scratch from Professionals?

Check out the Java training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this “Java ArrayList” blog and we will get back to you as soon as possible.

 

Comments
1 Comment

Browse Categories

Subscribe to our Newsletter, and get personalized recommendations.