ArrayList Class in Java With Program Example

Arraylist is a child class of AbstractList and implements List interface. It represents dynamic array that can grow or shrink as needed. In case of standard array, one must know the number of elements about to store in advance. In other words, a standard array is fixed in size and its size can’t be changed after its initialisation. To overcome this problem, collection framework provides ArrayList.

Point to Remember

1. It is a growable array
2. It allows duplicate elements
3. It preserves insertion order
4. It can store different types of elements
5. It can have null values
6. It resides in java.util package
7. By default, it is non synchronized class
8. It is not thread safe
9. It uses zero-based index to access, add, delete and update an element
10. If frequent operation is retrieve operation, then arrayList is best choice.
11. If insertion and removal in middle is the operation then arrayList is worst choice.
12. It doesn’t work with primitive types

Constructors in ArrayList

There are three constructors associated with ArrayList to create its objects.

1. new ArrayList() : A default constructor that takes no input and creates an empty list with default capacity. By default, it intializes with capacity of 10, meaning, it can hold 10 elements.

However,when an eleventh element is inserted in a list. JVM automatically generates a larger list with greater capacity and copies the element from old one to new one. Further, it changes reference variable to point to the new list, making old list eligible for garbage collection.

How to calculate capacity of ArrayList?

This is the formula used to calculate new capacity of an arrayList
new Capacity = (current capacity * 3/2)+1

ArrayList<ObjType> arr = new ArrayList<>();

2. new ArrayList ( int capacity) : A parameterised constructor that takes capacity as an input and creates an empty list with provided initial capacity.

ArrayList<ObjType> arr = new ArrayList<>(capacity);

3. new ArrayList (Collection c) : The constructor takes collection object as an input and creates an equivalent list from the given collection

ArrayList<ObjType> arr = new ArrayList<>(c);

The purpose of collection is to hold a group of data that can be transferred from one place to another place, it can be over the network or data sources. In order to provide this support, it is compulsory to implement serializable interface. Therefore, all the collection implementation classes implements serializable class.

Further, Arraylist and Vector implements RandomAccess interface that signifies accessing any element using index which takes same time.
RandomAccess interface is present in java.util packages and doesn’t consist any method. It’s a marker interface.

How to define an ArrayList?

ArrayList implements List interface and is a generic class with below definition:

ArrayList<ObjType> list = new ArrayList<>();
  • ObjType is any non-primitve dataType
  • new keyword is used to allocate memory and create an object.
  • ArrayList<>() is default constructor

 

Methods in Java ArrayList

MethodExplanation
add(T obj)It inserts an element to the end and returns true if the element is added successfully
add(int indx, T obj)It inserts the given element at the specified index of the list
addAll(Collection c)It adds entire compatiable collection objects to the end of the list
addAll(int indx, Collection c)It inserts all the compatiable collection objects at the given index in the list
clear() It removes or truncates all the elements from the given list
contains(Object obj) It returns true if the given object is present within the list
containsAll(Collection obj) It returns true if all the elements in the given collection are present in the list
equal(Object obj) It returns true if the given object is equivalent to the list
hashCode()It returns hashcode of a list
indexOf(Object c)It returns the index of the given object which matches first, oterwise -1 is returned
isEmpty()It check whether a list contains any element or not.
iterator() It returns iterator object for a list
lastIndexOf(Object obj)It returns index of the given object which match first from the last, otherwise, -1 is returned
listIterator() It returns object of ListIterator
listIterator(int indx)It returns listIterator object with the starting point specified with indx
remove(int index)It removes an element from the specified position and returns the removed object from the list
remove(Object obj)It removes very first occurrence of the given object from the list.
removeAll(Collection obj)It removes all the elements that are present in the given collection from the list
replaceAll(UnaryOperator operator)It replaces all the elements by performing the given operator to them in the list
retainAll(Collection c)It retains all the elements that matches in the given list and removes all others from the list
set(int indx, T obj)It replaces the given object at specified position and returns the replaced object.
size()It returns number of elements present in the list
sort(Comparator c)It sorts the list based on given order specified in the comparator
spliIterator()It returns SplitIterator object
subList(int from, int to) It returns sublist that falls between fromIndx and toIndex
toArray() It converts and returns an array corresponding to the given list
MethodsExplanation
add(T obj)It inserts an element to the end and returns true if it's added successfully
add(int indx, T obj)It inserts the given element at the specified index of the list
addAll(Collection c)It adds entire compatible collection objects to the end of the list
addAll(int indx, Collection c)It inserts all the compatiable collection objects at the given index in the list
clear()It removes or truncates all the elements from the given list
contains(Object obj)It returns true if the given object is present within the list
containsAll(Collection obj)It returns true if all the elements in the given collection are present in the list
equals(Object obj)It returns true if the given object is equivalent to the list
hashCode()It returns hashcode of a list
indexOf(Object c)It returns the index of the given object which matches first, oterwise -1 is returned
isEmpty()It checks whether a list contains any element or not.
iterator()It returns iterator object for a list
lastIndexOf(Object obj)It returns index of the given object which match first from the last, otherwise, -1 is returned
listIterator()It returns object of ListIterator
listIterator(int indx)It returns listIterator object with the starting point specified with indx.
remove(int index)It removes an element from the specified position and returns the removed object from the list
remove(Object obj)It removes very first occurrence of the given object from the list.
removeAll(Collection obj)It removes all the elements that are present in the given collection from the list
replaceAll(UnaryOperator operator)It replaces all the elements by performing the given operator to them in the list
retainAll(Collection c)It retains all the elements that matches in the given list and removes all others from the list
set(int indx, T obj)It replaces the given object at specified position and returns the replaced object.
size()It returns number of elements present in the list
sort(Comparator c)It sorts the list based on given order specified in the comparator.
spliIterator()It returns SplitIterator object
subList(int from, int to)It returns sublist that falls between fromIndx and toIndex
toArray()t converts and returns an array corresponding to the given list

Operations in ArrayList

There are various operations can be performed on a ArrayList. These are

1. Element addition
2. Element updation
3. Element deletion
4. Element traversal
5. Element access
6. Element sorting

1. Adding an element in an Array

ArrayList provides implementation to add() method inherited from List interface. There are overloaded versions of add() method.

add(obj) : It appends an element to the end of a list
add(indx,obj) : It adds an element at the given position in a list

Below is the simple java program to add an element in an ArrayList

Program:

public class ListDeclarationExample {

public static void main(String[] args) {
ArrayList<Integer> integerArrayList = new ArrayList<>();
integerArrayList.add(5);
integerArrayList.add(10);
integerArrayList.add(1);
System.out.println("The list content :: "+ integerArrayList);
}
}

Output:

The list content :: [5, 10, 1]

2. Updating or replacing an element in an ArrayList

ArrayList provides set() method to set or replace an element at given position. The method takes index and the element as an input to replace and uses the index to locate the position and replaces the element with new value.

set(indx, obj) : It replaces an element at the given position with the new element.

Below is the simple java program to replace or update an element in an ArrayList

Program:

public class ListDeclarationExample {

public static void main(String[] args) {
ArrayList<Integer> integerArrayList = new ArrayList<>();
integerArrayList.add(5);
integerArrayList.add(10);
integerArrayList.add(1);
System.out.println("The list :: "+ integerArrayList);

integerArrayList.set(1,100); // replacing element (10) at index 1 with 100

System.out.println(integerArrayList);
}
}

Output:

The list content :: [5, 10, 1]

3. Deleting an element from an ArrayList

remove() method is used to delete an element from a list. It has multiple overloaded versions. These are :

remove(obj) : It deletes very first occurrence of the matched object in a list.
remove(int indx): It deletes an element located at a given position or index

Below is the simple Java program to delete or remove an element from an ArrayList

Program:

public class ListDeclarationExample {

public static void main(String[] args) {
ArrayList<Integer> integerArrayList = new ArrayList<>();
integerArrayList.add(5);
integerArrayList.add(10);
integerArrayList.add(1);
System.out.println("The list :: "+ integerArrayList);

integerArrayList.remove(1); // removing element (10) at index 1

System.out.println(integerArrayList);
}
}

Output:

The list :: [5, 10, 1]
[5, 1]

4. Iterating over elements of an ArrayList

All the collection framework classes indirectly implements Iterable interface. The iterable interface provides various methods which empowers iterating ArrayList. These are :

Iterator() : It returns Iterator Object. It provides a way to iterate over a list
forEach(Consumer action) : It iterates and performs action over each element until all the element are processed.

Apart from this, for-each or advance for loop can be used to iterate through elements of a list

Below is the simple Java program to iterate through an ArrayList

Program:

public class ListDeclarationExample {

public static void main(String[] args) {
ArrayList<Integer> integerArrayList = new ArrayList<>();
integerArrayList.add(5);
integerArrayList.add(10);
integerArrayList.add(1);

System.out.println(" Iterating through iterator :: ");
Iterator itr = integerArrayList.iterator(); // getting iterator object from arraylist instance
while(itr.hasNext()) // while the list has the content, do
{
System.out.println(itr.next()); // returns the current element and moves the iteration state to next element
}

System.out.println(" Iterating through forEach :: ");
integerArrayList.forEach(System.out::println); // Java 8 forEach with lambda exp

System.out.println(" Iterating through for-each :: ");

for (Integer val:
integerArrayList) {
System.out.println(val);
}

}
}

Output:

Iterating through iterator ::
5
10
1
Iterating through forEach ::
5
10
1
Iterating through for-each ::
5
10
1

5. Fetching an element from an ArrayList

ArrayList uses zero-based index in order to access an element. It provides a method named get() that takes index as an input and returns the element at that position

get(indx) : returns an element at the given position

Below is the simple Java program to get or fetch an element from an ArrayList

Program:

public class ListDeclarationExample {

public static void main(String[] args) {
ArrayList<Integer> integerArrayList = new ArrayList<>();
integerArrayList.add(5);
integerArrayList.add(10);
integerArrayList.add(1);

System.out.println("Fetching element at index 2 :: "+ integerArrayList.get(2));

}
}

Output:

Fetching element at index 2 :: 1

7. Sorting elements in an ArrayList

Sort() method is used to sort a list in ArrayList. It takes comparator as an input and applies on elements to achieve sorting.

sort(Comparator c): sorts elements in a list

Below is the simple java program to sort an ArrayList

Program:

public class ListDeclarationExample {

public static void main(String[] args) {
ArrayList<Integer> integerArrayList = new ArrayList<>();
integerArrayList.add(5);
integerArrayList.add(10);
integerArrayList.add(1);
System.out.println("before sorting :: "+integerArrayList);

integerArrayList.sort(Comparator.comparingInt(Integer::intValue));
System.out.println("after sorting :: "+integerArrayList);

}
}

Output:

before sorting :: [5, 10, 1]
after sorting :: [1, 5, 10]

How to get length or size of an ArrayList?

size() method is used to get length or size of an array in arrayList.

size() : returns length of a list
integerArrayList.size();

 

Leave a Reply