Java ArrayList With Example

Java ArrayList
  • ArrayList is a resizable implementation of List interface, ArrayList can also be called as a dynamic Array.
  • Like Array, ArrayList stores similar data type elements which can increase its size dynamically.
  • ArrayList cannot store primitive data types like int and char, it can only store non-primitive data types like Integer, String, etc..
  • The index of the ArrayList starts with 0 as shown in the below picture.
Java ArrayList index

Example: Create an ArrayList called books which stores book names

import java.util.List;
import java.util.ArrayList;

public Class ArrayListDemo {
        List<String> books = new ArrayList<String>();
}

ArrayList and List are under Java utils package. List interface has other implementations besides ArrayList the below image shows them all.

List Interface and Implementation Classes

Common ArrayList Methods

  • add()
  • clear()
  • remove()
  • contains()
  • get()
  • index()
  • isEmpty()
  • sort()
  • size()
  • set()

add()

The method is used to add elements into the ArrayList, let’s add a couple of books to the ArrayList we created above

books.add("The Alchemist");
books.add("Four Hour Work Week");
books.add("Little Fires Everywhere");

clear()

The method is used to clear all elements from the ArrayList.

books.clear(); // clears the Arraylist books

remove()

The method remove takes index as a parameter and removes elements from that index.

books.remove(1); //removes the book titled "Four Hour Work Week" from the arraylist.

contains()

The method checks if the element exists in the ArrayList and returns true or false.

books.contains("Steve Jobs"); // returns boolean value false as it doesn't exists.

get()

The method is used to retrieve the ArrayList element from a particular index.

books.get(0); // returns "The Alchemist" as that is the book at index 0.

index()

This method is used to find the index of an element in the ArrayList.

books.index("Little Fires Everywhere"); //returns 2 the index of the book in the arraylist.

isEmpty()

Checks if the ArrayList is empty and returns a boolean value.

books.isEmpty();// returns false if not empty.

sort()

This method sorts the ArrayList in alphabetical order if it’s of type String or numerical if Integer type or follows the overridden methods if comparable methods are overridden.

books.sort();//reuslts is {"Four Hour Work Week", "Little Fires Everywhere", "The Alchemist"}

size()

This method returns the size of the ArrayList.

books.size(); // return 3 the size of ArrayList.

set(index i, Element e)

This method is used to replace an element at a particular index.

books.set(1, "Start With Why"); //results in {"Four Hour Work Week", "Start With Why", "The Alchemist"}

These are some of the most commonly used methods in an ArrayList in Java.

Below is the video tutorial explaining with a live demonstration.

Please subscribe to our Youtube Channel HackerHeap ClickHere