Java ArrayList
An ArrayList
in java is a dynamic data structure used for storing elements.ArrayList
is represented by java.util.ArrayList
class. It is dynamic since it automatically grows in size once it becomes full.
It is possible to add, remove, update elements in an ArrayList
.
You can insert elements at start, in between or at the end of an ArrayList
.
This article will cover Java ArrayList in detail. Below is the list of topics covered.
Class Hierarchy
ArrayList Syntax
ArrayList Constructors
Add element to ArrayList
Know to size of ArrayList
Get ArrayList elements
Update element value
Remove elements
Clearing or empty ArrayList
Convert ArrayList to string
Iterate or loop ArrayList
Sort ArrayList
ArrayList internal implementation
Polymorphism in ArrayList
Features of ArrayList
As stated above, an ArrayList
is dynamic, means its size is not fixed and increases as the elements are added.
Besides this, ArrayList
has the following attributes or characteristics.
1. Supports random access
Elements of an ArrayList
can be indexed in between. This means that you can directly retrieve nth element of an ArrayList
without going through n-1 elements.
This is because ArrayList
implements RandomAccess
interface. This is a marker interface that indicates that the classes implementing it supports random element access.
2. Faster iteration
Iterating an ArrayList
is faster as compared to an array or a LinkedList
.
3. Ordered
ArrayList
is an ordered collection. This means that elements are ordered in the order of their insertion.
Elements of ArrayList
are ordered by their index positions.
4. Unsorted
Elements of an ArrayList
are not sorted in any order.
5. Cloneable
It is possible to create clone of an ArrayList
. This is because it implements java.lang.Cloneable
interface.
6. Serializable
An ArrayList
can also be serialized since it implement java.io.Serializable
interface.
7. Type checking
ArrayList
should declare the type of elements that it will hold at the time of creation.
Thus, it provides compile time check before the elements adding elements so that only compatible type elements are added.
This prevents any run time exceptions.
ArrayList class hierarchy
ArrayList
is a part of Java Collections framework, hence it implements certain interfaces and extends classes.
Hierarchy of ArrayList
class can be understood with the following illustration.
As visible from above image, ArrayList
extends java.util.AbstractList
which contains methods common to all List implementations.
AbstractList
is a child class of java.util.AbstractCollection
which contains methods common to all Collection classes.
Both AbstractList
and AbstractCollection
are abstract classes and contain abstract methods which are implemented in concrete collection child classes.
ArrayList
implements java.util.List
interface. This interface is the parent interface for all linear list like data structures.List
interface in turn extends java.util.Collection
interface, the root interface of Java Collection framework.
ArrayList
also implements Cloneable
and Serializable
interfaces which allow its clone to be created and serialized respectively.
Finally, ArrayList
implements RandomAccess
due to which its elements can be randomly accessed faster.
ArrayList syntax
Since ArrayList
is a class, before using it you need to create its object.
Also, since ArrayList
is a collection designed to hold objects, it is generic. Thus, while creating an ArrayList
, you need to declare the type of objects that it will hold.
This type is declared after the name of class enclosed between angle brackets.
Below syntax will declare and create an ArrayList
of String
objects
ArrayList<String> list = new ArrayList<String>();
where list
is a reference variable for using the list later.
Type declaration at left side is called reference type while that at right side is called object type.
Since ArrayList
implements List
interface, the type of reference variable can also be a List
as shown below.
List<String> list = new ArrayList<String>();
Starting java 7, there is no need to declare the type at the right side since the compiler can infer it from the reference type.
Thus, above syntax can be simplified to
List<String> list = new ArrayList<>();
This is also called Diamond syntax since the two angle brackets at the right resemble a diamond.
ArrayList constructors
Constructor of a class is used while creating its object.
ArrayList class has 2 overloaded constructors.
1. public ArrayList()
This is a no-argument constructor and creates an ArrayList
with a pre-defined fixed length.
Default length of an ArrayList
is 10.
That is, when the ArrayList
is created using the no-argument constructor, its length or capacity is set to 10.
2. public ArrayList(int capacity)
This constructor accepts a numeric argument and creates an ArrayList
with the given capacity.
ArrayList add element
ArrayList
provides add method to add an element. There are two overloaded versions of add()
method.
1. add(E)
This method accepts the element to be added and adds it to the end of the list. Example,
List<Integer> list = new ArrayList<>(); list.add(5);
2. add(index, E)
This method accepts an element and the index at which this element will be added. Index is 0 based.
Example,
List<String> list = new ArrayList<>(); list.add(2, "Collections");
This will add the element at third position in the list.
All the elements starting from the given index are shifted to the right in order to create space for the element to be inserted.
ArrayList size
Size of ArrayList
is the number of elements in it.
Size of an ArrayList
can be determined using its size()
method.
Do not confuse size with the length or capacity of ArrayList
.
For an empty ArrayList
, return value of size()
will be 0.
ArrayList get element
In order to retrieve an element from ArrayList
, use its get
method.get()
accepts a numeric argument which is the index of the element that needs to be fetched. Example,
List<Integer> list = new ArrayList<>(); // add elements Integer e = list.get(3);
This will fetch the element at index 3 or the fourth list element.
Note that the type of variable to which the element is assigned is of the same type as the Arraylist
.
ArrayList set element
Element at a specified position can also be updated or modified in an ArrayList
using its set
method.set()
method accepts two arguments:
first is the index at which the element should be updated. Index is 0-based.
second is the value to be updated.
Example,
List<Integer> list = new ArrayList<>(); // add elements list.set(3, 54);
Update the value of fourth element to 54.set()
method returns the older value of the element before being updated.
ArrayList remove element
ArrayList
provides 2 overloaded methods to remove an element.
1. remove(index)
Removes the element from the given index. Index is 0 based.
This method returns the object removed from the ArrayList
.
Elements to the right of the removed element are shifted to the left to fill up the empty space. Example,
List<Integer> list = new ArrayList<>(); // add elements list.remove(3);
This example removes or deletes the fourth element of the list.
2. remove(element)
This method accepts the element to be removed. If there are more than two elements with the same value, then it removes the first occurrence of the element.
This method returns true
if the object was successfully removed from the ArrayList
.
Example,
List<String> list = new ArrayList<>(); // add elements Integer e = list.remove("Hello");
If you have an ArrayList
of custom objects such as Student objects and you need to delete students on the basis of roll numbers(for example), then you need to override equals method for defining the criteria of removal.
In case equals is not overridden, then remove
will invoke equals
method of Object
class and compare object references to remove objects.
ArrayList clear
ArrayList has a clear()
method which removes all its elements and makes the list empty. Example,
ArrayList<Integer> list = new ArrayList<>(); // add 4 integers System.out.println("Size of list is: " + list.size()); // clear list.clear(); System.out.println("Size of list is now: " + list.size());
which prints
Size of list is: 4
Size of list is now: 0
After clear()
method is called, size of list will be 0.
ArrayList toString()
An ArrayList
can be converted to a String
. This is generally done to print its contents.
In order to convert an ArrayList
to a String
, call toString()
method on ArrayList
object.
java.util.AbstractCollection
which is the super parent of ArrayList
overrides toString()
method from java.lang.Object
.
When toString()
is invoked, it encloses the elements of ArrayList
within square brackets and returns it in String format. Example,
ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(45); list.add(63); list.add(65); System.out.println(list.toString());
This prints
Loop ArrayList
Since the elements of ArrayList are index based, it can be iterated using a traditional for loop or enhanced for loop as shown below.
ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(45); list.add(63); list.add(65); list.add(23); list.add(76); System.out.println("With indexed for loop"); for (int i = 0; i < list.size(); i++) { Integer element = list.get(i); System.out.print(element + " "); } System.out.println("\n----------------------------"); System.out.println("With indexed for loop"); for (Integer element : list) { System.out.print(element + " "); }
With a simple for
loop, an element is retrieved using its get()
method while with enhanced for loop, get()
is not required as the loop variable holds the current list element in each iteration.
Above example prints
With indexed for loop
1 45 63 65 23 76
—————————-
With indexed for loop
1 45 63 65 23 76
There are many different ways of iterating over an ArrayList other than those explained above such as using an iterator in java.
Sort ArrayList
Sorting means arranging the elements of ArrayList
in some order.ArrayList
can be sorted using sort method of java.util.Collections
class. Example,
// create list List<Integer> list = new ArrayList<>(); // add elements list.add(3); list.add(1); list.add(19); list.add(190); list.add(102); System.out.println("Before sorting"); System.out.println(list.toString()); // sort list Collections.sort(list); System.out.println("After sorting"); System.out.println(list.toString());
This prints
Before sorting
3, 1, 19, 190, 102
After sorting
1, 3, 19, 102, 190
For Collections.sort
to work correctly, objects of ArrayList
must implement java.lang.Comparable
.String
, Integer
and all wrapper class implement this interface.
If you need to sort ArrayList
of custom objects, then simply using Collections.sort
would not work. Refer this post to sort ArrayList
of objects.
ArrayList java implementation
This is one of the most commonly asked interview questions.ArrayList
in java api is implemented as an array. The type of array is java.lang.Object
.
This makes sense since the type of ArrayList
is not known till it is created and an Object
array can hold objects of any type.
Thus, when an ArrayList
is created, then internally an array is initialized as shown below.
this.elementData = new Object[initialCapacity];
initialCapacity
is the integer supplied through the constructor.
If no-argument constructor is used, initialCapacity
is set to 10.
When the element is added using add
method , then before performing the operation, the array is checked for the capacity.
If the array is full, then it is increased by the initial capacity.
Polymorphism in ArrayList
Reference type and object type of ArrayList
can not be polymorphic. Thus, below declaration is invalid.
ArrayList<Number> list = new ArrayList<Integer>();
This means that you can not use a super class as the reference type and its sub-class as the object type. They both need to be same.
However, the type of ArrayList
can be polymorphic. Below declaration is allowed.
List<Integer> list = new ArrayList<Integer>();
Since ArrayList
implements List
interface.
Polymorphism also exists while adding elements to ArrayList. You can add objects of type Square, Circle, Rectangle to an ArrayList
of type Shape.
Hope the article was useful.