ArrayList in Java

Let’s create an ArrayList object named elements which stores string elements:

import java.util.ArrayList; // Importing the ArrayList class from the java.util package

// Creating an ArrayList to store String elements
ArrayList elements = new ArrayList();

Java ArrayList is a part of the Java collections framework and it is a class of java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. This class is found in java.util package. The main advantage of ArrayList in Java is, that if we declare an array then we need to mention the size, but in ArrayList, it is not needed to mention the size of ArrayList. If you want to mention the size then you can do it.

Table of Content

What is ArrayList in Java?

ArrayList is a Java class implemented using the List interface. Java ArrayList, as the name suggests, provides the functionality of a dynamic array where the size is not fixed as an array. Also, as a part of the Collections framework, it has many features not available with arrays.

ArrayList Java

Illustration:

Let us check on the ArrayList with the Integer Object type Stored in it with a image.

ArrayList_Integer_Object

Java ArrayList Example

Example 1: The following implementation demonstrates how to create and use an ArrayList with a mention of its size.


Output
Array 1:[] Array 2:[] Array 1:[1, 2, 3, 4, 5] Array 2:[1, 2, 3, 4, 5]

Explanation of the above Program:

ArrayList is a dynamic array and we do not have to specify the size while creating it, the size of the array automatically increases when we dynamically add and remove items. Though the actual library implementation may be more complex, the following is a very basic idea explaining the working of the array when the array becomes full and if we try to add an item:

Important Features of ArrayList in Java

Let’s understand the Java ArrayList in depth . Look at the below image:

List Classes Interface

In the above illustration, AbstractList , CopyOnWriteArrayList , and AbstractSequentialList are the classes that implement the list interface. A separate functionality is implemented in each of the mentioned classes. They are:

  1. AbstractList: This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods.
  2. CopyOnWriteArrayList: This class implements the list interface. It is an enhanced version of ArrayList in which all the modifications(add, set, remove, etc.) are implemented by making a fresh copy of the list.
  3. AbstractSequentialList: This class implements the Collection interface and the AbstractCollection class. This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods.

Constructors in ArrayList in Java

In order to Create an ArrayList, we need to create an object of the ArrayList class. The ArrayList class consists of various constructors which allow the possible creation of the array list. The following are the constructors available in this class:

1. ArrayList()

This constructor is used to build an empty array list. If we wish to create an empty ArrayList with the name arr , then, it can be created as:

ArrayList arr = new ArrayList(); 

2. ArrayList(Collection c)

This constructor is used to build an array list initialized with the elements from the collection c. Suppose, we wish to create an ArrayList arr which contains the elements present in the collection c, then, it can be created as:

ArrayList arr = new ArrayList(c); 

3. ArrayList(int capacity)

This constructor is used to build an array list with the initial capacity being specified. Suppose we wish to create an ArrayList with the initial size being N, then, it can be created as:

ArrayList arr = new ArrayList(N);

Java ArrayList Methods

Method Description
add(int index, Object element) This method is used to insert a specific element at a specific position index in a list.
add(Object o) This method is used to append a specific element to the end of a list.
addAll(Collection C) This method is used to append all the elements from a specific collection to the end of the mentioned list, in such an order that the values are returned by the specified collection’s iterator.
addAll(int index, Collection C) Used to insert all of the elements starting at the specified position from a specific collection into the mentioned list.
clear() This method is used to remove all the elements from any list.
clone() This method is used to return a shallow copy of an ArrayList in Java.
contains? (Object o) Returns true if this list contains the specified element.
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.
forEach?(Consumer action) Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
get?(int index) Returns the element at the specified position in this list.
indexOf(Object O) The index the first occurrence of a specific element is either returned or -1 in case the element is not in the list.
isEmpty?() Returns true if this list contains no elements.
lastIndexOf(Object O) The index of the last occurrence of a specific element is either returned or -1 in case the element is not in the list.
listIterator?() Returns a list iterator over the elements in this list (in proper sequence).
listIterator?(int index) Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.
remove?(int index) Removes the element at the specified position in this list.
remove? (Object o) Removes the first occurrence of the specified element from this list, if it is present.
removeAll?(Collection c) Removes from this list all of its elements that are contained in the specified collection.
removeIf?(Predicate filter) Removes all of the elements of this collection that satisfy the given predicate.
removeRange?(int fromIndex, int toIndex) Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive.
retainAll?(Collection c) Retains only the elements in this list that are contained in the specified collection.
set?(int index, E element) Replaces the element at the specified position in this list with the specified element.
size?() Returns the number of elements in this list.
spliterator?() Creates a late-binding and fail-fast Spliterator over the elements in this list.
subList?(int fromIndex, int toIndex) Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
toArray() This method is used to return an array containing all of the elements in the list in the correct order.
toArray(Object[] O) It is also used to return an array containing all of the elements in this list in the correct order same as the previous method.
trimToSize() This method is used to trim the capacity of the instance of the ArrayList to the list’s current size.

Note: You can also create a generic ArrayList:

// Creating generic integer ArrayList
ArrayList arrli = new ArrayList();

Some Key Points of ArrayList in Java

  1. ArrayList is Underlined data Structure Resizable Array or Growable Array.
  2. ArrayList Duplicates Are Allowed.
  3. Insertion Order is Preserved.
  4. Heterogeneous objects are allowed.
  5. Null insertion is possible.

Let’s see how to perform some basic operations on the ArrayList as listed which we are going to discuss further alongside implementing every operation.

Operations performed in ArrayList

1. Adding Elements

In order to add an element to an ArrayList, we can use the add() method . This method is overloaded to perform multiple operations based on different parameters. They are as follows:

Below is the implementation of the above approach:


Output
[Geeks, For, Geeks]

2. Changing Elements

After adding the elements, if we wish to change the element, it can be done using the set() method. Since an ArrayList is indexed, the element which we wish to change is referenced by the index of the element. Therefore, this method takes an index and the updated element which needs to be inserted at that index.

Below is the implementation of the above approach:


Output
Initial ArrayList [Geeks, Geeks, Geeks] Updated ArrayList [Geeks, For, Geeks]

3. Removing Elements

In order to remove an element from an ArrayList, we can use the remove() method . This method is overloaded to perform multiple operations based on different parameters. They are as follows:

Example:


Output
Initial ArrayList [Geeks, For, Geeks] After the Index Removal [Geeks, Geeks] After the Object Removal [Geeks]

4. Iterating the ArrayList

There are multiple ways to iterate through the ArrayList. The most famous ways are by using the basic for loop in combination with a get() method to get the element at a specific index and the advanced for a loop .

Example


Output
Geeks For Geeks Geeks For Geeks

5. Get Elements


Output
[9, 5, 6] at indext 1 number is:5

6. Add Elements Between Two Numbers


Output
[1, 2, 4] [1, 2, 3, 4]

7. ArrayList Sort


Output
Before sorting list: [2, 4, 3, 1] after sorting list: [1, 2, 3, 4]

8. Size of Elements


Output
The size is :4

Complexity of Java ArrayList

Inserting Element in ArrayList

Removing Element from ArrayList

Traversing Elements in ArrayList

Replacing Elements in ArrayList

ArrayList in Java is a class in the Java Collections framework that implements the List interface. Here are the advantages and disadvantages of using ArrayList in Java.

Advantages of Java ArrayList

Disadvantages of Java ArrayList

Conclusion

Points to be remembered from this article are mentioned below:

FAQs of ArrayList

What is an ArrayList in Java?

An ArrayList is a resizable array that is part of the Java Collections Framework. It can dynamically grow and shrink as elements are added or removed.

How is ArrayList different from an Array in Java?

An ArrayList can resize dynamically, while a traditional array has a fixed size. ArrayList also provides many useful methods like add() , remove() , and size() .

How to Create an ArrayList in Java?

Can ArrayList hold primitive types like int or char?

No, ArrayList can only hold objects. You must use wrapper classes like Integer or Character .

How to Add elements to an ArrayList?

We can add elements using the add() method:

How to Access elements in an ArrayList?

Elements can be accessed using the get() method:

String element = list.get(0);

How to Remove an element from an ArrayList?

Use the remove() method to remove elements by index:

list.remove(0);

Is ArrayList Synchronized?

No, ArrayList is not synchronized. Use Collections.synchronizedList(new ArrayList<>()) for thread-safe operations.

Can we Store null elements in an ArrayList?

Yes, ArrayList can store null elements.

How to convert an ArrayList to an Array?

We can convert an ArrayList to an array using the toArray() method:

String[] array = list.toArray(new String[0]);

How is data stored in ArrayList?

ArrayList can store data till the ArrayList size is full, after that the size of ArrayList is doubled if we want to store any more elements.

Does ArrayList allow Duplicates?

Yes, ArrayList allows duplicate values to be stored.