AppDividend
Latest Code Tutorials

Java ArrayList Example | Array List in Java Tutorial From Scratch

0

Java ArrayList Example | ArrayList in Java Tutorial is today’s topic. ArrayList in Java is used to save the dynamically sized collection of items. Arrays are fixed in size; an ArrayList grows its size automatically when new items are added to it. ArrayList is the part of collection framework and is present in the java.util package. ArrayList inherits the AbstractList class and implements List interface.

Important Points about ArrayList

  1. It can be compared as a Vector in C++.
  2. We cannot use primitive data type like char, int, float.
  3. We always need to use wrapper class 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 its size to accept new elements and contracts the size when the elements are removed.
  6. ArrayList internally uses an array to store the elements. Just 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 insertion order of the elements.
  9. Java ArrayList is not synchronized. If the multiple threads try to modify the ArrayList at the same time, 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 new generic collection allows you to have only one type of object in the collection. Now it is type safe so typecasting is not required at runtime.

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

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

Let’s see the new generic example of creating 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 the only specified type of objects in it. If you try to add a different kind of object, it gives 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 the initial size being specified.

Java ArrayList Example

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

In this lesson, we will discuss all the methods and its usages.

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

import java.util.ArrayList

ArrayList Initialization:

We can initialize the ArrayList in Java using the following code.

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

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

Add elements to the ArrayList

If we want to add items to the declared ArrayList, we have to call add() method and pass the value as argument which we want to add in the ArrayList.

Syntax

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

All the elements will add in the ArrayList in a contiguous manner. And indexing will be the same as an array. i.e., 1st elements 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);
    }
}

The output is following.

Java ArrayList Example

 

Accessing Elements in ArrayList

We can access elements in ArrayList using the get () method.

Syntax:

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

The output is: “apple.

In this get () method we need to 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 following.

Accessing Elements in ArrayList

 

How to Change Elements in ArrayList

We can change the element by calling the set() method in ArrayList.

See the following syntax of the ArrayList set() method.

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);

    }
}

The output is following.

How to Change Elements in ArrayList

 

 

Find Size of ArrayList

We can find the size of ArrayList using the size() method.

See the below syntax for ArrayList size() method.

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

See the following example of the ArrayList size() method.

// 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());

    }
}

The output is following.

Find Size of ArrayList

 

How To Remove Item From ArrayList

We can remove elements from an ArrayList using the remove() method.

The syntax for Java ArrayList remove() method is following.

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);

    }
}

The output is following.

How To Remove Item From ArrayList

 

Display items in ArrayList

We can print all the elements of an ArrayList using a for loop, size() method and get() method.

The syntax is following.

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));
        }

    }
}

The output is following.

Display items in ArrayList

 

How To Clear All Items From ArrayList

We can remove all the items from the ArrayList using the clear() method.

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

We can check if the ArrayList is empty or not using the ArrayList isEmpty() function.

See the following code.

// 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());
    }
}

The output is following.

How to check if an ArrayList is empty

 

Creating an ArrayList from another collection

We can create another ArrayList from another collection using the ArrayList(Collection c) constructor.

See the following code 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("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 assign the thrones collection to that ArrayList. Now, the output is following.

 

Creating an ArrayList from another collection

Iterating over an ArrayList

There are various ways to traverse the collection elements. Below are the most used methods.

  1. By 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);
        });
    }
}

The output is following.

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 item is being 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);
        }

    }
}

The output is following.

Iterator Interface in ArrayList

 

ListIterator Interface in ArrayList

The listIterator() method of java.util.ArrayList class is used to return 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());
        }

    }
}

The output is following.

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 they are returned by the specified collection’s iterator.
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 is used to return an array containing all of the elements in this list in the correct order.
<T> T[] toArray(T[] a) It is used to return 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 is used to remove 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 is used to remove 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 is used to replace 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 that are present in the specified collection.
E set(int index, E element) It is used to replace the specified item in the list, present at the specific position.
void sort(Comparator<? super E> c) It is used to sort the items of the list on the basis of the specified comparator.
Spliterator<E> spliterator() It is used to create spliterator over the items in a list.
List<E> subList(int fromIndex, int toIndex) It is used to fetch all the items occupies 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.

 

Conclusively, Java ArrayList Example | Array List in Java Tutorial is over.

Leave A Reply

Your email address will not be published.

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