Java ArrayList class

An ArrayList in Java represents a resizable list of objects. We can add, remove, find, sort and replace elements in this list.

ArrayList is part of the collections framework. It extends AbstractList which implements List interface. The List extends Collection and Iterable interfaces in hierarchical order.

ArrayList Hierarchy
ArrayList Hierarchy

1. ArrayList Features

ArrayList has the following features –

  1. Ordered – Elements in ArrayList preserve their ordering which is by default the order in which these were added to the list.
  2. Index-based – Elements can be randomly accessed using index positions. Index starts with '0'.
  3. Dynamic resizingArrayList grows dynamically when more elements need to be added than its current size.
  4. Non-synchronized – ArrayList is not synchronized by default. The programmer needs to use the synchronized keyword appropriately or simply use the Vector class.
  5. Duplicates allowed – We can add duplicate elements in ArrayList. It is not possible in sets.

2. How does ArrayList Works?

ArrayList class is implemented with a backing array. The elements added or removed from ArrayList are actually modified in the backing array. All ArrayList methods access this backing array and get/set elements in the same array.

ArrayList can be seen as resizable-array implementation in Java.

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, 
               Cloneable, java.io.Serializable
{
  transient Object[] elementData;   //backing array
  private int size;         //array or list size
 
  //more code
}

3. Java Array vs. ArrayList

An array is a fixed-size data structure where the size has to be declared during initialization. Once the size of an array is declared, it is impossible to resize the array without creating a new one.

Integer[] numArray = new Integer[5];

The ArrayList offers to remove this sizing limitation. An ArrayList can be created with any initial size (default 16), and when we add more items, the size of the ArrayList grows dynamically without any intervention by the programmer.

ArrayList<Integer> numList = new ArrayList<>();

Many people refer to ArrayList as dynamic array.

4. Creating an ArrayList

4.1. How to create an ArrayList

To create ArrayList, we can call one of its constructors.

ConstructorDescription
ArrayList()It is the default constructor. It creates an empty ArrayList with an initial capacity of 16.
ArrayList(int capacity)It creates an empty ArrayList with the given initial capacity.
ArrayList(Collection<? extends E> c)It creates an ArrayList that is initialized with the elements of the collection c.

Given below program shows how to declare and initialize an ArrayList in Java.

ArrayList list = new ArrayList();
 
List<Integer> numbers = new ArrayList<>(6); 
 
Collection setOfElements = ...;
List<Integer> numbers = new ArrayList<>(setOfElements); 

4.2. Generic ArrayList

A generic ArrayList clearly mentions the type of objects it will store. It helps in avoiding a lot of defects caused by incorrect typecasting.

//Non-generic arraylist - NOT RECOMMENDED !!
ArrayList list = new ArrayList();
 
//Generic Arraylist with default capacity
List<Integer> numbers = new ArrayList<>(); 
 
//Generic Arraylist with the given capacity
List<Integer> numbers = new ArrayList<>(6); 
 
//Generic Arraylist initialized with another collection
List<Integer> numbers = new ArrayList<>( Arrays.asList(1,2,3,4,5) ); 

4.3. ArrayList of primitive types

In ArrayList, we are supposed to add only objects. But in case we are required to add primitive data types such as int, float etc, we can use their wrapper classes for providing type information during ArrayList initialization.

When we add the int or float value to ArrayList, values are automatically upcasted.

In given an example, we have created an array list of Integer values. When we add int value 1, it is automatically converted to new Integer(1).

List<Integer> numbers = new ArrayList<>(6); 
 
numbers.add(1); // This runs fine

4.4. Create and initialize ArrayList in single line

Generally, creating an arraylist is a multi-step process. In first step, we create an empty array list. In later steps, we populate the list with elements – one by one.

Using Arrays.asList() and constructor ArrayList(collection), we can combine these steps in a single statement.

ArrayList<String> charList = new ArrayList<>(Arrays.asList(("A", "B", "C"));

5. Get element from ArrayList

To get an element from the ArrayList, we have two ways.

5.1. get(index)

If we know the index location in advance, then we can call the get(index) which returns the element present at index location.

Please remember that indexes start with zero.

ArrayList<String> alphabetsList = new ArrayList<>(Arrays.asList(("A", "B", "C"));
 
String aChar = alphabetsList.get(0);  // A

5.2. iterator.next()

Use iterator() or listIterator() to get the reference of Iterator instance. We can use this iterator to iterate the elements in the ArrayList.

The next() method returns the element at the current index location and increments the index count by one. Call hasNext() method to check if there are more elements in the list to iterate.

ArrayList<Integer> digits = new ArrayList<>(Arrays.asList(1,2,3,4,5,6));
 
Iterator<Integer> iterator = digits.iterator();
 
while(iterator.hasNext()) 
{
  System.out.println(iterator.next());
}

Program output.

1
2
3
4
5
6

6. Iterating over an ArrayList

6.1. Iterator

Java example of iterating over an ArrayList using the Iterator.

ArrayList<Integer> digits = new ArrayList<>(Arrays.asList(1,2,3,4,5,6));
 
Iterator<Integer> iterator = digits.iterator();
 
while(iterator.hasNext()) 
{
  System.out.println(iterator.next());
}

6.2. For loop

Java example of iterating over an ArrayList using for loop. When using for loop, we need to get the current element using the current index counter.

ArrayList<Integer> digits = new ArrayList<>(Arrays.asList(1,2,3,4,5,6));
 
for(int i = 0; i < digits.size(); i++) 
{
    System.out.print(digits.get(i));
}

6.3. forEach loop

forEach loop works pretty much the same as simple for loop. The only difference is that the JVM manages the counter initialization and increment. We get the next element in each iteration in the loop.

ArrayList<Integer> digits = new ArrayList<>(Arrays.asList(1,2,3,4,5,6));
 
for(Integer d : digits) 
{
    System.out.print(d);
}

7. Finding the length of the ArrayList

To get the size of the ArrayList, we use the size() method.

ArrayList<Integer> digits = new ArrayList<>(Arrays.asList(1,2,3,4,5,6));
 
System.out.print( digits.size() );    // 6

8. Sorting an ArrayList

ArrayList sort() method sorts the list according to the order induced by the specified Comparator instance. All elements in the list must be mutually Comparable.

public class AgeSorter implements Comparator<Employee> 
{
    @Override
    public int compare(Employee e1, Employee e2) {
        //comparison logic
    }
}
ArrayList<Employee> employees = new ArrayList<>();
 
employees.add(new Employee(...));
employees.add(new Employee(...));
employees.add(new Employee(...));
 
employees.sort(new NameSorter());

9. Conclusion

In this Java tutorial, we learned to work with ArrayList in Java. We learned to create, modify and perform advanced operations in the ArrayList class.

Happy Learning !!

Sourcecode on Github

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.