Java ArrayList: The Complete Guide

0
76
Java ArrayList Example | Array List in Java Tutorial From Scratch

ArrayList is part of the collection framework and is present in java.util package. ArrayList inherits the AbstractList class and implements the List interface.

Java ArrayList

Java ArrayList is a part of a built-in collection framework used to save the dynamically sized collection of elements. Arrays are fixed in size; an ArrayList grows its size automatically when new items are added to it.

The ArrayList class in Java is a resizable array found in java.util package.

Important Points about ArrayList in Java

  1. It can be compared to a Vector in C++.
  2. We cannot use primitive data types like char, int, or float.
  3. We always need wrapper classes like Integer, String, Float, etc. 
  4. Java ArrayList allows us to access the list randomly.
  5. An ArrayList is the re-sizable array, also called a dynamic array. It grows to accept new elements and contracts its size when removed.
  6. ArrayList internally uses an array to store the elements. Like arrays, It allows you to fetch the elements by their index.
  7. Java ArrayList allows duplicate and null values.
  8. Java ArrayList is the ordered collection. It maintains the insertion order of the elements.
  9. Java ArrayList is not synchronized. If multiple threads try to modify the ArrayList simultaneously, then the outcome will be non-deterministic. You must explicitly synchronize access to the ArrayList if multiple threads are going to change it.

Java Non-generic Vs. Generic Collection

Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.

Java’s new generic collection allows you to have only one type of object in the collection. In addition, now it is type-safe, so typecasting is not required at runtime.

Let’s see the old non-generic example of creating a Java collection.

ArrayList al=new ArrayList();//creating old non-generic arraylist

Let’s see the new generic example of creating a java collection.

ArrayList<String> al=new ArrayList<String>();//creating new generic arraylist

In a generic collection, we specify the type in angular braces. Now ArrayList is forced to have only specified types of objects in it. If you try to add a different kind of object, it gives a compile-time error.

Constructors in Java ArrayList

  1. ArrayList(): This constructor is used to build an empty array list
  2. ArrayList(Collection c): This constructor is used to construct an array list initialized with the elements from collection c.
  3. ArrayList(int capacity): This constructor is used to build an array list with a specified initial size.

Example

If we want to remove the limitations of an array, there is a different class name, ArrayList, which helps us to use the array dynamically. It is found in package java.util.

In this lesson, we will discuss all the methods and their usage.

If we want to use this class, we need to import the class using the following line of code.

import java.util.ArrayList

How to initialize ArrayList in Java

To initialize an ArrayList in Java, use the new keyword.

ArrayList<data type >name_ofArrayList=new ArrayList<datatype>()

First, in the angular bracket, we need to provide the data type we want to use in the ArrayList. i.e., int, float, String, etc.

Java ArrayList add

To add elements in Java ArrayList, use the add() method. The java.util.ArrayList.add() function inserts the specified item at the specified position in this list. Pass the value as the argument we want to add to the ArrayList.

Syntax

ArrayList <String> al =new ArrayList<String>();
al.add(“apple”);
al.add(“banana”);
al.add(“mango”);

All the elements will add to the ArrayList in a contiguous manner. And indexing will be the same as an array. i.e., 1st element will have 0 indexes, for 2nd index value will be 1, and so on.

See the following example of adding items to the Java ArrayList.

// ArrayListC.java

import java.util.ArrayList;

public class ArrayListC {

    public static void main(String[] args) {
        // Creating an ArrayList of String
        ArrayList<String> thrones = new ArrayList<>();

        // Adding new elements to the ArrayList
        thrones.add("Arya");
        thrones.add("Tyrion");
        thrones.add("Jon");
        thrones.add("Daenerys");

        System.out.println(thrones);
    }
}

See the output.

Java ArrayList Example

How to access ArrayList elements in Java

To access ArrayList elements in Java, use the get() method. The get() method of ArrayList is used to get the item of a specified index within the list.

Syntax:

al.get(0); // it will fetch the first element of ArrayList

The output is: “apple.

In this get () method, we must pass the index value to fetch the elements.

See the following example of accessing items in ArrayList.

// ArrayListC.java

import java.util.ArrayList;

public class ArrayListC {

    public static void main(String[] args) {
        // Creating an ArrayList of String
        ArrayList<String> thrones = new ArrayList<>();

        // Adding new elements to the ArrayList
        thrones.add("Arya");
        thrones.add("Tyrion");
        thrones.add("Jon");
        thrones.add("Daenerys");

        System.out.println(thrones.get(0));
        System.out.println(thrones.get(1));
        System.out.println(thrones.get(2));
        System.out.println(thrones.get(3));
    }
}

The output of the above code is the following.

Accessing Elements in ArrayList

How to change elements in ArrayList

To change elements in ArrayList, use the set() method. The set() is a built-in java.util.ArrayList class replaces the element at the specified position in this list with the specified element.

Syntax

al.set(0, “value”);

In the first index, the item will be changed, and the new item will be “value”.

See the following example.

// ArrayListC.java

import java.util.ArrayList;


public class ArrayListC {

    public static void main(String[] args) {
        // Creating an ArrayList of String
        ArrayList<String> thrones = new ArrayList<>();

        // Adding new elements to the ArrayList
        thrones.add("Arya");
        thrones.add("Tyrion");
        thrones.add("Jon");
        thrones.add("Daenerys");
        System.out.println("Before the modification of List:" +thrones);
        thrones.set(1, "Jaime");
        thrones.set(2, "Sansa");
        System.out.println("-----------------------------------------");
        System.out.println("After the modification of List:" +thrones);

    }
}

See the output.

How to Change Elements in ArrayList

Java ArrayList length

To find the length of ArrayList in Java, use the size() method. The size() is a built-in Java method that returns an integer equal to number of elements in the array list.

Syntax

al.size(); //It will calculate  number of elements in ArrayList

Example

// ArrayListC.java

import java.util.ArrayList;

public class ArrayListC {

    public static void main(String[] args) {
        // Creating an ArrayList of String
        ArrayList<String> thrones = new ArrayList<>();

        // Adding new elements to the ArrayList
        thrones.add("Arya");
        thrones.add("Tyrion");
        thrones.add("Jon");
        thrones.add("Daenerys");
        System.out.println("Size of ArrayList: " + thrones.size());

    }
}

See the output.

Find Size of ArrayList

How to remove an element from ArrayList

To remove an element from a Java ArrayList, use the remove() method. The ArrayList.remove() function removes an item at the specified position in the list.

Syntax

al.remove(0); //it will remove element from the first index

See the below example.

// ArrayListC.java

import java.util.ArrayList;

public class ArrayListC {

    public static void main(String[] args) {
        // Creating an ArrayList of String
        ArrayList<String> thrones = new ArrayList<>();

        // Adding new elements to the ArrayList
        thrones.add("Arya");
        thrones.add("Tyrion");
        thrones.add("Jon");
        thrones.add("Daenerys");

        thrones.remove(0);
        System.out.println(" Remaining items of the ArrayList: " + thrones);

    }
}

See the output.

How To Remove Item From ArrayList

How to display elements in ArrayList

To display elements in ArrayList, use the get() method. Print all the elements of an ArrayList using a for loop, size() method, and get() method.

for(int I; i<al.size();i++)               
{
   System.out.println(al.get(i));      
}

See the following example.

// ArrayListC.java

import java.util.ArrayList;

public class ArrayListC {

    public static void main(String[] args) {
        // Creating an ArrayList of String
        ArrayList<String> thrones = new ArrayList<>();

        // Adding new elements to the ArrayList
        thrones.add("Arya");
        thrones.add("Tyrion");
        thrones.add("Jon");
        thrones.add("Daenerys");

        for(int i = 0; i<thrones.size(); i++)
        {
            System.out.println(thrones.get(i));
        }

    }
}

See the output.

Display items in ArrayList

How to clear all elements from ArrayList

To clear all the elements from an ArrayList in Java, use the clear() method. The clear() is a built-in Java method of ArrayList in Java that removes all the elements from a list.

Syntax

al.clear();// delete all the elements from the ArrayList

It will remove all the items from an ArrayList.

See the following code.

// ArrayListC.java

import java.util.ArrayList;

public class ArrayListC {

    public static void main(String[] args) {
        // Creating an ArrayList of String
        ArrayList<String> thrones = new ArrayList<>();

        // Adding new elements to the ArrayList
        thrones.add("Arya");
        thrones.add("Tyrion");
        thrones.add("Jon");
        thrones.add("Daenerys");

        System.out.println("Before clearing the ArrayList: " + thrones);
        thrones.clear();
        System.out.println("-----------------------------------------");
        System.out.println("After clearing the ArrayList: " + thrones);
    }
}

It will remove all the elements from the ArrayList.

How to check if an ArrayList is empty

To check if an ArrayList is empty in Java, use the ArrayList isEmpty() function. ArrayList isEmpty() method is used to check whether the list is empty.

// ArrayC.java

import java.util.ArrayList;

public class ArrayListC {

    public static void main(String[] args) {
        // Creating an ArrayList of String
        ArrayList<String> thrones = new ArrayList<>();

        // Adding new elements to the ArrayList
        thrones.add("Arya");
        thrones.add("Tyrion");
        thrones.add("Jon");
        thrones.add("Daenerys");

        thrones.clear();

        System.out.println("ArrayList is empty true or false: " + thrones.isEmpty());
    }
}

See the output.

How to check if an ArrayList is empty

How to create an ArrayList from another collection

To create an ArrayList from another collection in Java, use the ArrayList(Collection c) constructor.

// ArrayListC.java

import java.util.ArrayList;

public class ArrayListC {

    public static void main(String[] args) {
        // Creating an ArrayList of String
        ArrayList<String> thrones = new ArrayList<>();

        // Adding new elements to the ArrayList
        thrones.add("Lyana");
        thrones.add("Edd");
        thrones.add("Viserion");
        thrones.add("Giants");

        ArrayList<String> whitewalkers = new ArrayList<>(thrones);
        System.out.println("We have created a collection from thrones: " + whitewalkers);

    }
}

So, first, we have created an ArrayList called thrones, and then we have initialized another ArrayList called whitewalkers and assigned the thrones collection to that ArrayList.

See the output.

Creating an ArrayList from another collection

Iterating over an ArrayList

To iterate ArrayList in Java,

  1. By the Iterator interface.
  2. By ListIterator interface.
  3. By for loop(We have seen earlier in the post).
  4. By forEach() method.

forEach loop in ArrayList

Let’s iterate ArrayList using a forEach loop. See the below code.

// ArrayListC.java

import java.util.ArrayList;

public class ArrayListC {

    public static void main(String[] args) {
        // Creating an ArrayList of String
        ArrayList<String> thrones = new ArrayList<>();

        // Adding new elements to the ArrayList
        thrones.add("Lyana");
        thrones.add("Edd");
        thrones.add("Viserion");
        thrones.add("Giants");

        thrones.forEach(character -> {
            System.out.println(character);
        });
    }
}

See the output.

forEach loop in ArrayList

Iterator Interface in ArrayList

For Iterator Interface, first, we need to import the package called java.util.Iterator. Then we use the constructor to create an iterator called throneIterator and call the next() method on it.

Until the last element is iterated, it continues to iterate. We need a while loop to iterate all the elements. See the below code example.

// ArrayListC.java

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListC {

    public static void main(String[] args) {
        // Creating an ArrayList of String
        ArrayList<String> thrones = new ArrayList<>();

        // Adding new elements to the ArrayList
        thrones.add("Lyana");
        thrones.add("Edd");
        thrones.add("Viserion");
        thrones.add("Giants");

        Iterator<String> throneIterator = thrones.iterator();
        while (throneIterator.hasNext()) {
            String character = throneIterator.next();
            System.out.println(character);
        }

    }
}

See the output.

Iterator Interface in ArrayList

ListIterator Interface in ArrayList

The listIterator() method of java.util.ArrayList class returns a list iterator over the elements in this list (in proper sequence). The returned list iterator is fail-fast. See the following example code.

// ArrayListC.java

import java.util.ArrayList;
import java.util.ListIterator;

public class ArrayListC {

    public static void main(String[] args) {
        // Creating an ArrayList of String
        ArrayList<String> thrones = new ArrayList<>();

        // Adding new elements to the ArrayList
        thrones.add("Lyana");
        thrones.add("Edd");
        thrones.add("Viserion");
        thrones.add("Giants");

        ListIterator<String> throneListIterator = thrones.listIterator();
        while (throneListIterator.hasNext()) {
            System.out.println(throneListIterator.next());
        }

    }
}

See the output.

ListIterator Interface in ArrayList

Methods of Java ArrayList

The following table has every method in the Java ArrayList example.

Method Description
void add(int index, E element) It is used to insert the specified item at the specified position in a list.
boolean add(E e) It is used to append the specified item at the end of a list.
boolean addAll(Collection<? extends E> c) It is used to append all of the items in the specified collection to the end of this list in the order that the specified collection’s iterator returns them.
boolean addAll(int index, Collection<? extends E> c) It is used to append all the items in the specified collection, starting at the specified position of the list.
void clear() It is used to remove all of the items from this list.
void ensureCapacity(int requiredCapacity) It is used to enhance the capacity of an ArrayList instance.
E get(int index) It is used to fetch the element from the particular position of the list.
boolean isEmpty() It returns true if the list is empty. Otherwise false.
int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence of the specified element, or -1, if the list does not contain this element.
Object[] toArray() It returns an array containing all of the elements in this list in the correct order.
<T> T[] toArray(T[] a) It returns an array containing all of the elements in this list in the correct order.
Object clone() It is used to return a shallow copy of an ArrayList.
boolean contains(Object o) It returns true if the list contains the specified element
int indexOf(Object o) It is used to return the index in this list of the first occurrence of the specified item, or -1 if the List does not contain this item.
E remove(int index) It removes the item present at the specified position in the list.
Boolean remove(Object o) It is used to remove the first occurrence of the specified item.
boolean removeAll(Collection<?> c) It is used to remove all the items from the list.
boolean removeIf(Predicate<? super E> filter) It removes all the items from the list that satisfies the given predicate.
protected void removeRange(int fromIndex, int toIndex) It is used to remove all the items lies within the given range.
void replaceAll(UnaryOperator<E> operator) It replaces all the items from the list with the specified element.
void retainAll(Collection<?> c) It is used to preserve all the items in the list in the specified collection.
E set(int index, E element) It is used to replace the specified item in the list at the specific position.
void sort(Comparator<? super E> c) It is used to sort the items on the list based on the specified comparator.
Spliterator<E> spliterator() It is used to create a spliterator over the items in a list.
List<E> subList(int fromIndex, int toIndex) It is used to fetch all the items occupied within the given range.
int size() It is used to return the number of elements present in a list.
void trimToSize() It is used to trim the capacity of this ArrayList instance to be the list’s current size.

 

That’s it.

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.