Arraylist

ArrayList is a part of collection framework and is present in java.util package. It provides us with dynamic arrays in Java.

Features of Arraylist

  • ArrayList inherits AbstractList class and implements the List interface.

  • ArrayList is initialized by the size. However, the size is increased automatically if the collection grows or shrinks if the objects are removed from the collection.

  • Java ArrayList allows us to randomly access the list.

  • ArrayList can not be used for primitive types, like int, char, etc. We need a wrapper class for such cases.

  • ArrayList in Java can be seen as a vector in C++.

  • ArrayList is not Synchronized. Its equivalent synchronized class in Java is Vector.

AbstractList

This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods.

CopyOnWriteArrayList

This class implements the list interface. It is an enhanced version of ArrayList in which all the modifications(add, set, remove, etc.) are implemented by making a fresh copy of the list.

AbstractSequentialList

This class implements the Collection interface and the AbstractCollection class. This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods.

Constructors in the ArrayList

ArrayList()

This constructor is used to build an empty array list. If we wish to create an empty ArrayList with the name arr, then, it can be created as

ArrayList arr = new ArrayList(); 

ArrayList(Collection c)

This constructor is used to build an array list initialized with the elements from the collection c. Suppose, we wish to create an ArrayList arr which contains the elements present in the collection c, then, it can be created as:

ArrayList arr = new ArrayList(c); 

ArrayList(int capacity)

This constructor is used to build an array list with initial capacity being specified. Suppose we wish to create an ArrayList with the initial size being N, then, it can be created as:

ArrayList arr = new ArrayList(N);  

Methods in ArrayList

MethodDescription
add(int index, Object element)This method is used to insert a specific element at a specific position index in a list.
add(Object o)This method is used to append a specific element to the end of a list.
addAll(Collection C)This method is used to append all the elements from a specific collection to the end of the mentioned list, in such an order that the values are returned by the specified collection’s iterator.
addAll(int index, Collection C)Used to insert all of the elements starting at the specified position from a specific collection into the mentioned list.
clear()This method is used to remove all the elements from any list.
clone()This method is used to return a shallow copy of an ArrayList.
contains?(Object o)Returns true if this list contains the specified element.
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.
forEach?(Consumer<? super E> action)Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
get?(int index)Returns the element at the specified position in this list.
indexOf(Object O)The index the first occurrence of a specific element is either returned, or -1 in case the element is not in the list.
isEmpty?()Returns true if this list contains no elements.
lastIndexOf(Object O)The index of the last occurrence of a specific element is either returned or -1 in case the element is not in the list.
listIterator?()Returns a list iterator over the elements in this list (in proper sequence).
listIterator?(int index)Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.

Operations on the ArrayList

Adding Elements

In order to add an element to an ArrayList, we can use the add() method. This method is overloaded to perform multiple operations based on different parameters. They are as follows:

  • add(Object): This method is used to add an element at the end of the ArrayList.

  • add(int index, Object): This method is used to add an element at a specific index in the ArrayList.

// Java Program to Add elements to An ArrayList

// Importing all utility classes
import java.util.*;

// Main class
class TFT {

	// Main driver method
	public static void main(String args[])
	{
		// Creating an Array of string type
		ArrayList<String> al = new ArrayList<>();

		// Adding elements to ArrayList
		// Custom inputs
		al.add("Tit");
		al.add("Tat");

		// Here we are mentioning the index
		// at which it is to be added
		al.add(1, "For");

		// Printing all the elements in an ArrayList
		System.out.println(al);
	}
}

Output

[Tit, For, Tat]

Changing Elements

After adding the elements, if we wish to change the element, it can be done using the set() method. Since an ArrayList is indexed, the element which we wish to change is referenced by the index of the element. Therefore, this method takes an index and the updated element which needs to be inserted at that index.

// Java Program to Change elements in ArrayList

// Importing all utility classes
import java.util.*;

// main class
class TFT {

	// Main driver method
	public static void main(String args[])
	{
		// Creating an Arraylist object of string type
		ArrayList<String> al = new ArrayList<>();

		// Adding elements to Arraylist
		// Custom input elements
		al.add("Tit");
		al.add("Tat");

		// Adding specifying the index to be added
		al.add(1, "For");

		// Printing the Arraylist elements
		System.out.println("Initial ArrayList " + al);

		// Setting element at 1st index
		al.set(1, "For");

		// Printing the updated Arraylist
		System.out.println("Updated ArrayList " + al);
	}
}

Output

Initial ArrayList [Tit, For, Tat]
Updated ArrayList [Tit, For, Tat]

Removing Elements

In order to remove an element from an ArrayList, we can use the remove() method. This method is overloaded to perform multiple operations based on different parameters. They are as follows:

  • remove(Object): This method is used to simply remove an object from the ArrayList. If there are multiple such objects, then the first occurrence of the object is removed.

  • remove(int index): Since an ArrayList is indexed, this method takes an integer value which simply removes the element present at that specific index in the ArrayList. After removing the element, all the elements are moved to the left to fill the space and the indices of the objects are updated.

// Java program to Remove Elements in ArrayList

// Importing all utility classes
import java.util.*;

import java.util.*;

// Main class
class TFT {

    // Main driver method
    public static void main(String args[])
    {
        // Creating an object of arraylist class
        ArrayList<String> al = new ArrayList<>();

        // Adding elements to ArrayList
        // Custom addition
        al.add("Tit");
        al.add("Tat");
        // Adding element at specific index
        al.add(1, "For");

        // Printing all elements of ArrayList
        System.out.println("Initial ArrayList " + al);

        // Removing element from above ArrayList
        al.remove(1);

        // Printing the updated Arraylist elements
        System.out.println("After the Index Removal " + al);

        // Removing this word element in ArrayList
        al.remove("Tit");

        // Now printing updated ArrayList
        System.out.println("After the Object Removal "
                + al);
    }
}

Output

Initial ArrayList [Tit, For, Tat]
After the Index Removal [Tit, Tat]
After the Object Removal [Tat]

Iterating the ArrayList

There are multiple ways to iterate through the ArrayList. The most famous ways are by using the basic for loop in combination with a get() method to get the element at a specific index and the advanced for loop.

// Java program to Iterate the elements
// in an ArrayList

// Importing all utility classes
import java.util.*;

// Main class
class TFT {

    // Main driver method
    public static void main(String args[])
    {
        // Creating an Arraylist of string type
        ArrayList<String> al = new ArrayList<>();

        // Adding elements to ArrayList
        // using standard add() method
        al.add("Tit");
        al.add("Tat");
        al.add(1, "For");

        // Using the Get method and the
        // for loop
        for (int i = 0; i < al.size(); i++) {

            System.out.print(al.get(i) + " ");
        }

        System.out.println();

        // Using the for each loop
        for (String str : al)
            System.out.print(str + " ");
    }
}

Output

Tit For Tat 
Tit For Tat 
core java programming array list collections

Subscribe For More Content