ArrayList in Java

ArrayList is a resizeable array implementation of the List interface. It implements all of the list operations and provides methods to manipulate the size of an array that is used internally to store the elements. ArrayList class is equivalent to the Vector class, except that it is unsynchronized.

We can think of ArrayList as a dynamic array whose size can grow or shrink per the requirement. It is a part of the Collection framework and was introduced in Java 1.2.

Some points about the ArrayList class
  • ArrayList size can grow or shrink as we add or remove the elements from the list.
  • ArrayList maintains the insertion order.
  • We can randomly access the elements of an ArrayList.
  • ArrayList class is the equivalent of the Vector class of Java, except that it is not synchronized and has much faster execution. So, we can use ArrayList, where we don’t need a thread-safe environment.
  • Iterators returned by the ArrayList class iterator and listiterator are fail-fast which will be discussed later in the post.
  • We cannot create an ArrayList of the primitive types like int, float, etc. We have to use their corresponding wrapper classes.

Declaration of the ArrayList class

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
ArrayList class structure

Constructors of the ArrayList class

Java ArrayList class has three overloaded constructors –

  • public ArrayList() – It creates an empty list with an initial capacity of 10.
  • public ArrayList(int initialCapacity) – It also creates an empty ArrayList with the specified initial capacity.
  • public ArrayList(Collection c) – It creates a list containing all of the elements of the Collection passed in the argument, in the order returned by the Collection’s iterator.
Creating an empty ArrayList with the default constructor
public class Codekru {

	public static void main(String[] args) throws Exception {

		ArrayList<String> al = new ArrayList<String>(); // an empty array list
													// with an intial capacity of 10

	}
}
Creating an empty ArrayList with an initial capacity
public class Codekru {

	public static void main(String[] args) throws Exception {

		ArrayList<String> al = new ArrayList<String>(5); // an empty array list
															// with an intial capacity of 5

	}
}

Generic v/s Non-generic ArrayList

We can make two kinds of ArrayList, one is generic, and the other is non-generic.

A Non-generic list can have any type of element, like a String or an Integer, while the generic ones can only have one type of element. It’s preferable to use the generic ArrayList over the Non-generic ones because it helps in preventing a lot of issues caused by incorrect typecasting.

Non-Generic ArrayList
ArrayList al = new ArrayList();
Generic ArrayList
ArrayList<String> al = new ArrayList<String>(); // generic list containing elements
												// of type "String"

ArrayList<Integer> al = new ArrayList<Integer>(); // generic list containing elements
														// of type "Integer"

Adding elements into an ArrayList

We can easily add elements into an ArrayList using the add() function, which we are going to discuss in detail in another post. Below is a simple example of how to add elements into an ArrayList.

public class Codekru {

	public static void main(String[] args) throws Exception {

		ArrayList<String> al = new ArrayList<String>(); // generic list containing elements
														// of type "String"

		// adding the elements into the arraylist
		al.add("hello");
		al.add("codekru");

		System.out.println("ArrayList content: " + al.toString()); // printing the arraylist

	}
}

Output –

ArrayList content: [hello, codekru]
How does ArrayList work internally, and how does it increase its size to store more elements?
  • ArrayList uses a capacity value much like the vector’s capacity with some implementation differences.
  • When we create an ArrayList object, a default capacity of 10 is assigned to the list internally even though the size of the array list is still 0.
  • Now, when the capacity of the array list becomes equal to its size, then the capacity of the array list is increased to adjust more elements.
  • We can say that capacity of an array list is always greater than or equal to its size. We can also assign an initial capacity ourselves while making an ArrayList but make sure to use an optimal capacity which can reduce the amount of incremental reallocation that needs to be done while adding the elements.

Now, what about those fail-fast iterators that we talked about earlier

Iterator is one of the ways to iterate over an ArrayList. The iterator returned by the ArrayList class iterator and the listIterator methods is fail-fast which means if the list is structurally modified after creating the iterator in any way, except using the iterator’s own remove or add methods, then the iterator will throw a ConcurrentModificationException.

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

public class Codekru {

	public static void main(String[] args) {

		ArrayList<String> al = new ArrayList<String>();

		al.add("first"); // appending the element at the end of the list
		al.add("second");

		Iterator<String> it = al.iterator();

		// iterating over the array
		while (it.hasNext()) {
			System.out.println(it.next());
		}

		// adding the third element
		al.add("third");

		// Now, iterating over the list will throw an exception
		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}
}

Output –

first
second
Exception in thread "main" java.util.ConcurrentModificationException
	at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1013)
	at java.base/java.util.ArrayList$Itr.next(ArrayList.java:967)

ArrayList methods

Method name What does it do?
public boolean add(E e) It appends the specified element to the end of the list.
public void add(int index, E element) It inserts the specified element at the specified position in the list.
public boolean addAll(Collection c) It appends all elements in the specified Collection to the end of the list.
public boolean addAll(int index, Collection c) It inserts all of the elements in the specified Collection into the list at the specified position.
public void clear() It removes all of the elements from the list.
public Object clone() It returns the clone of the list.
public boolean contains(Object o) It tells us whether the list contains the specified element or not.
public boolean containsAll(Collection<?> c) It tells us whether the list contains all of the elements of the specified collection or not.
public void ensureCapacity(int minCapacity) If necessary, it increases the capacity of the ArrayList to ensure that it can hold at least the number of components specified by the minimum capacity argument.
public synchronized E get(int index) It returns the element at the specified position of the list.
public int indexOf(Object o) It returns the index of the first occurrence of the specified element.
public boolean isEmpty() It tells whether the list has any components or not.
public int lastIndexOf(Object o) It returns the index of the list’s last occurrence of the specified element.
public E remove(int index) It removes the element at the specified position of the list.
public boolean remove(Object o) It removes the first occurrence of the specified element in the list.
public boolean removeAll(Collection<?> c)  It removes all of the elements present in the collection from the list.
public E set(int index, E element) It replaces the element at the specified position in the list with the specified element.
public int size() It returns the number of components in the list.
public List subList(int fromIndex, int toIndex) It returns a view of the portion of this List between fromIndex( inclusive ) and toIndex ( exclusive).
public Object[] toArray() It returns an array containing all the list elements in the correct order.
public void trimToSize() It trims the capacity of the list to be the list’s current size.

We hope that you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at [email protected].

Referenced Article – https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html

Related Articles
Liked the article? Share this on

Leave a Comment

Your email address will not be published. Required fields are marked *