Java ArrayList class

The java.util.ArrayList class is a very useful class in the Collections framework. It is basically a resizable-array implementation of the List interface. ArrayList extends AbstractList class and implements List Interface.

An ArrayList in Java represent a resizable list of objects. It is widely used because of the functionality and flexibility it offers. Most of the Java developers choose ArrayList over arrays as it is a very good alternative of traditional arrays. We can easily add, remove, find, sort and replace elements in this list.

 

ArrayList Class Constructors

Following is the list of constructors provided by the Java ArrayList class.

Sl. No.

Constructor and Description

1

ArrayList( )

This constructor builds an empty array list.

2

ArrayList (Collection c)

This constructor builds an array list that is initialized with the elements of the collection c.

3

ArrayList (int capacity)

This constructor builds an array list that has the specified initial capacity. The capacity is the size of the underlying array that is used to store the elements. The capacity grows automatically as elements are added to an array list.

 

ArrayList Class Methods

Apart from the methods inherited from its super classes and super interfaces, ArrayList defines the following methods

Sl. No.

Method and Description

1

void add (int index, Object element)

Inserts the specified element at the specified position index in this list. Throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index > size()).

2

boolean add (Object o)

Appends the specified element to the end of this list.

3

boolean addAll (Collection c)

Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s iterator. Throws NullPointerException, if the specified collection is null.

4

boolean addAll (int index, Collection c)

Inserts all of the elements in the specified collection into this list, starting at the specified position. Throws NullPointerException if the specified collection is null.

5

void clear()

Removes all of the elements from this list.

6

Object clone()

Returns a shallow copy of this ArrayList.

7

boolean contains (Object o)

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

8

void 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.

9

Object get (int index)

Returns the element at the specified position in this list. Throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index >= size()).

10

int indexOf (Object o)

Returns the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.

11

int lastIndexOf (Object o)

Returns the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.

12

Object remove (int index)

Removes the element at the specified position in this list. Throws IndexOutOfBoundsException if the index out is of range (index < 0 || index >= size()).

13

protected void removeRange (int fromIndex, int toIndex)

Removes from this List all of the elements whose index is between fromIndex, inclusive and toIndex, exclusive.

14

Object set (int index, Object element)

Replaces the element at the specified position in this list with the specified element. Throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index >= size()).

15

int size()

Returns the number of elements in this list.

16

Object[ ] toArray()

Returns an array containing all of the elements in this list in the correct order. Throws NullPointerException if the specified array is null.

17

Object[ ] toArray (Object[ ] a)

Returns an array containing all of the elements in this list in the correct order; the runtime type of the returned array is that of the specified array.

18

void trimToSize()

Trims the capacity of this ArrayList instance to be the list’s current size.

NOTE: ArrayList class does not have any capacity() method unlike Vector class. So, ArrayList has to use ensureCapacity() method which increases the capacity of its instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.

 

Example 1

The following program illustrates several of the methods supported by the ArrayList class.

ArrayListDemo1.java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;

public class ArrayListDemo1 {

public static void main(String[] args) {
// Create an ArrayList of different types (non-generic style)
ArrayList list1 = new ArrayList();

// Add elements to ArrayList
list1.add(10);
list1.add(45.37);
list1.add(true);
list1.add('O');
list1.add("JAVA");
System.out.println("List1: " + list1);
System.out.println("Size: " + list1.size());

// Ensure that ArrayList can hold up to 50 elements
list1.ensureCapacity(50);
System.out.println("ArrayList list1 can now store up to 50 elements.");

// Create an ArrayList of Integers using Generics
ArrayList<Integer> list2 = new ArrayList<Integer>(Arrays.asList(74, 49, 25, 34, 57));
// Add Elements
list2.add(62);
list2.add(16);
// Remove Elements
list2.remove(6); // remove element at index 6
list2.remove(new Integer(74)); // remove element 74

System.out.println("\nList2: " + list2);
System.out.println("Size: " + list2.size());
// Sort the array list
Collections.sort(list2);
System.out.println("Sorted ArrayList: " + list2);

// Create an ArrayList of Strings with initial capacity 20
ArrayList<String> list3 = new ArrayList<String>(20);

// Add new elements to list2
list3.add("Book");
list3.add("Diary");
list3.add("Pen");
System.out.println("\nList3: " + list3);
System.out.println("Size: " + list3.size());

// Add more elements to list2
list3.add("Eraser");
list3.add(3, "Pencil");

System.out.println("Modified list3 elements are:~ ");
// Iterate through the elements of ArrayList
Iterator it = list3.iterator();
while (it.hasNext()) {
System.out.print(it.next() + " ");
}
System.out.println();

// Create an array of String type
String[] arr = {"Dog", "Cat", "Horse"};
// Create an ArrayList from an array
ArrayList<String> animals = new ArrayList<>(Arrays.asList(arr));

// Create another ArrayList
ArrayList<String> extra_animals = new ArrayList<>(Arrays.asList("Cow", "Goat"));

// Create ArrayList using Collection object as argument of constructor
ArrayList<String> list4 = new ArrayList<>(animals); //Java SE 8 style
// Appends all of the elements in the specified collection to the end of the list4
list4.addAll(extra_animals);
System.out.println("\nArrayList list4 elements are:~ ");
list4.forEach(System.out::println);
System.out.println();

// Create a new array of String type
String[] array = new String[list4.size()];
// Convert ArrayList into an array
list4.toArray(array);

System.out.print("Array for list4: ");
// Access the elements using get() method
for(int i=0; i<array.length; i++) {
System.out.print(list4.get(i)+ " ");
}
System.out.println();

list4.removeAll(list4);
System.out.println("List4 after removal: " + list4);
}
}

Output:

List1: [10, 45.37, true, O, JAVA]
Size: 5
ArrayList list1 can now store up to 50 elements.

List2: [49, 25, 34, 57, 62]
Size: 5
Sorted ArrayList: [25, 34, 49, 57, 62]

List3: [Book, Diary, Pen]
Size: 3
Modified list3 elements are:~
Book Diary Pen Pencil Eraser

ArrayList list4 elements are:~
Dog
Cat
Horse
Cow
Goat

Array for list4: Dog Cat Horse Cow Goat
List4 after removal: []

 

Example 2

The following program creates an ArrayList of objects of class type Book (user-defined class).

ArrayListDemo2.java

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

class Book {
String title, author;
int id, pages, year;
double price;

public Book(String title, String author, int id, int pages, int year, double price) {
this.title = title;
this.author = author;
this.id = id;
this.pages = pages;
this.year = year;
this.price = price;
}

@Override
public String toString() {
return "(Title: " + title + "; Author: " + author + "; Id: " + id + "; Pages: " + pages + "; Yesr: " + year + "; Price: " + price + ")";
}
}

public class ArrayListDemo2 {

public static void main(String[] args) {
// Creating an ArrayList of objects of class type Book
ArrayList<Book> ab = new ArrayList<Book>();
ab.add(new Book("Let Us C", "Kanetkar", 101, 500, 1998, 225.25));
ab.add(new Book("Java Complete Reference", "Schildt", 102, 1000, 1996, 455.75));
ab.add(new Book("Basic Electrical", "Thereja", 103, 600, 1995, 325.95));
ab.add(new Book("Digital Logic", "Mano", 104, 495, 1993, 275.95));
ab.add(new Book("Discrete Mathematics", "Rosen", 105, 1300, 1991, 695.95));

System.out.println("ArrayList Contents:~ ");
System.out.println("===================");
Iterator ite = ab.iterator();
int i = 0;
while (ite.hasNext()) {
System.out.println("Book " + (i + 1) + " = " + ite.next() + " ");
i++;
}
System.out.println();

}
}

Output:

ArrayList Contents:~ 
===================
Book 1 = (Title: Let Us C; Author: Kanetkar; Id: 101; Pages: 500; Yesr: 1998; Price: 225.25)
Book 2 = (Title: Java Complete Reference; Author: Schildt; Id: 102; Pages: 1000; Yesr: 1996; Price: 455.75)
Book 3 = (Title: Basic Electrical; Author: Thereja; Id: 103; Pages: 600; Yesr: 1995; Price: 325.95)
Book 4 = (Title: Digital Logic; Author: Mano; Id: 104; Pages: 495; Yesr: 1993; Price: 275.95)
Book 5 = (Title: Discrete Mathematics; Author: Rosen; Id: 105; Pages: 1300; Yesr: 1991; Price: 695.95)