Java ArrayList Tutorial with Examples

Java Arraylist tutorial with examples will help you understand how to use ArrayList in Java in an easy way. ArrayList in Java is an implementation of the List interface which grows automatically as we add elements to it.

Difference between array and ArrayList: Java arrays are fixed in size, which means the size of an array cannot be changed once it is created, while the ArrayList in Java can grow and shrink in size as we add or remove elements from it. Java ArrayList uses an array internally to store its elements.

Java ArrayList Tutorial

The ArrayList class implements all the optional operations defined by the List interface. It also allows null elements. Like an array, elements of an ArrayList can be accessed using an index. ArrayList index starts from 0 to ArrayList.size() – 1. The ArrayList class is a part of the Java Collection Framework.

Since the ArrayList class also implements the RandomAccess interface, its elements can be accessed randomly by specifying the index. This operation is a constant time operation.

The length of an internal array maintained by the ArrayList is called the capacity of the ArrayList. As you add elements to the ArrayList, the ArrayList capacity grows automatically.

How to create an ArrayList object?

The ArrayList class in Java provides several constructors using which we can create new objects of the ArrayList class. The default constructor of the ArrayList class creates a new empty ArrayList object. The below given statement will create an empty ArrayList of String type.

There is an overloaded ArrayList constructor that accepts the Collection type as a parameter.

This constructor creates an ArrayList object containing all the elements of the specified collection. Below given example shows how to copy an ArrayList to another ArrayList using this constructor.

Output

How to add elements to ArrayList using the add method?

The add method of the ArrayList class adds the specified element at the end of the ArrayList object.

Output

Please note that primitive type like int or double cannot be added to the ArrayList, only objects can be. if you want to store primitive types, you can first convert it to the respective wrapper objects like Integer or Double and then add them to the ArrayList.

How to insert an element in the ArrayList at the specified index using the add method?

The above given add method appends an element at the end of the ArrayList. What if you want to insert an element in between or at the specified index? Well, there is an overloaded add method that accepts the element to insert as well as the index to which we want to insert an element.

This method inserts an element at the given index in the ArrayList and shifts subsequent elements to the right (i.e. 1 is added to their existing index).

Output

As you can see from the output, the element 22 is inserted at index 2. The element 3 was previously at index 2, but now it is shifted to the right by adding 1 to its index.

How to add an element at the front of the ArrayList?

The default add method appends an element at the end of the ArrayList. If you want to add an element at the front of the ArrayList or the start of the ArryList, use the add method with the element and index parameters and specify the index as 0.

Output

How to replace an element in the ArrayList using the set method?

The set method of the ArrayList class replaces an element with the specified new element located at the given index. It returns the old element which was replaced by the new element at the specified index.

Output

Note: Always make sure to check the size first to avoid the IndexOutOfBoundsException while replacing an element in the ArrayList.

How to get the size of an ArrayList using the size method (ArrayList length)?

The size method of the ArrayList class returns the number of elements that are stored in the ArrayList object. It returns 0 if the ArrayList is empty.

Output

How to get elements from an ArrayList using the get method?

The get method of the ArrayList in Java returns an element stored at the specified index. ArrayList index starts at 0 and ends at ArrayList’s size – 1 index.

Output

Note: Always make sure to check the size of the ArrayList object before getting the element using the index. The get method throws IndexOutOfBoundsException exception if the specified index is out of the range i.e. if the index is less than 0 or index is greater than or equal to the ArrayList size.

How to get the first element of an ArrayList?

Since the ArrayList index starts at 0, the first element of an ArrayList is located at index 0, not 1. Use the get method and specify the index 0 to get the first element of the ArrayList.

Output

How to get the last element of an ArrayList?

The ArrayList index ends at the size – 1 index. So, the last element of the ArrayList is located at that index.

Output

How to check if ArrayList is empty using the isEmpty method?

The isEmpty method of the ArrayList class returns true if the ArrayList contains no elements. If the ArrayList contains at least one element, it returns false.

Output

You can also compare the ArrayList size with 0 to check if the ArrayList is empty. However, the isEmpty method is recommended way to check as it clearly states the purpose of the code and it more readable.

How to check if ArrayList contains the specified element using the contains method?

The contains method returns true if the ArrayList contains the specified element. It returns false if the list does not contain the specified element.

Output

The contains method returns a boolean indicating whether the ArrayList contains an element or not. If you want to get the index of the element in the ArrayList, use the below given indexOf and lastIndexOf methods.

How to search elements in the ArrayList using the indexOf and lastIndexOf methods?

How to search the first occurrence of the element using the indexOf method?

The indexOf method returns the index of the first occurrence of the specified element in the ArrayList. If the list does not contain the specified element, it returns -1.

Output

How to search the last occurrence of the element using the lastIndexOf method?

The lastIndexOf method returns the index of the last occurrence of the specified element in the ArrayList. It returns -1 if the element is not found in the ArrayList.

Output

How to Iterate ArrayList in Java?

There are several ways using which you can iterate ArrayList in Java.

1. Iterate ArrayList using a while loop

2. Iterate ArrayList using a for loop

3. Iterate ArrayList using an enhanced for loop

4. Iterate ArrayList using Iterator

5. Iterate ArrayList using ListIterator

The below given example shows how to iterate an ArrayList in reverse direction of backward direction using the ListIterator.

Output

Please visit how to iterate ArrayList in Java example to know more.

How to remove elements from the ArrayList?

1. How to remove an element from the ArrayList using the remove method?

The remove method removes an element at the specified index of the ArrayList object. All the subsequent elements are shifted to the left by reducing their indices by 1. The remove method returns an element that was removed from the list.

Example:

Output

There is an overloaded remove method that takes an Object as an argument instead of the index.

If the list contains the specified element, the remove method removes the first occurrence of the specified object from the ArrayList and returns true. If the list does not contain the specified element, the list remains unchanged and this method returns false.

Output

Please note that only the first occurrence of the specified object is removed from the ArrayList.

2. How to remove an element from the ArrayList using the iterator?

The remove method of an Iterator removes an element from the underlying ArrayList while iterating over ArrayList elements.

Output

3. How to remove an element from the ArrayList using the ListIterator?

Just like the Iterator, you can use the remove method of the ListIterator class to remove the current element from the ArrayList while iterating over its elements.

Output

4. How to remove all elements from the ArrayList using the clear method?

The clear method removes all elements from the ArrayList object. The ArrayList becomes empty after this method call.

Output

5. How to remove all elements within the given range using the removeRange method?

The removeRange method removes all the elements from the ArrayList object whose index is between the specified start index and end index. The start index is inclusive while the end index is exclusive.

The problem is, the removeRange method is declared as protected, so only classes in the same package or the subclasses of an ArrayList class can access this method. If you want to use this method, you need to create your own implementation by extending the ArrayList class as given in the below example.

Output

6. How to remove all elements of an ArrayList which are present in another ArrayList?

The removeAll method removes all the elements from the ArrayList which are also present in the specified Collection object. The removeAll method returns true if the ArrayList is changed as a result of the method call.

The below given example shows how to remove all elements from one ArrayList which are also present in another ArrayList object.

Output

Since the removeAll method accepts the Collection type, you can use any class that implements the Collection interface instead of an ArrayList.

How to clone the ArrayList using the clone method?

The clone method of the ArrayList returns a shallow copy of this ArrayList object. A shallow copy means only the element references are copied, not the element objects themselves.

Output

Please visit How to deep clone an ArrayList example to know more about deep cloning the ArrayList in Java.

How to convert ArrayList to an array using the toArray method?

The toArray method of the ArrayList class returns an array containing all elements of this ArrayList (converts ArrayList to array).

Output

If the specified array is large enough to hold all the elements of an array, the toArray method returns the same array filled with the elements of the ArrayList. If the specified array is bigger than the ArrayList, the remaining elements of the array are filled with the null elements. If the specified array is smaller than the ArrayList size, a new array is allocated, filled with the ArrayList elements and returned.

Even though you can pass an array of any length to the toArray method, it is always recommended to pass the array of the same size to the toArray method to avoid the performance penalty of the creation of a new array.

What is ArrayList capacity?

The ArrayList class internally maintains an array to store its elements. The size of this internal array or buffer is known as the ArrayList capacity. ArrayList grows automatically as and when we add more elements to it by allocating a new bigger size array.

Why do we need to bother about the ArrayList capacity if it is automatically managed by the ArrayList class? Well, the allocation of a new array is a costly operation in terms of performance. Imagine you have an ArrayList having 1,00,000 elements and you want to add 50,000 more elements to it. In that case, the ArrayList class has to allocate new memory for an array big enough to hold the 1,50,000 elements and copy all existing 1,00,000 elements to the new bigger array. This is a very very costly operation.

We can avoid this if we know the approximate number of elements ArrayList is going to hold beforehand. We can then create an ArrayList object with the required capacity to avoid the reallocation when we add elements to it. The below given constructor creates an ArrayList with the specified capacity.

If you want to add a very large number of elements to an existing ArrayList object, you can use the ensureCapacity method first to make sure that the ArrayList can hold at least the specified number of elements before reallocation of an internal buffer is needed.

Please visit the ArrayList capacity tutorial to know more about how to efficiently manage the capacity of ArrayList.

How to get the sublist from the ArrayList using the subList method?

The subList method returns a portion of the ArrayList containing elements whose index is between the given start and end index.

The startIndex is inclusive while the endIndex is exclusive, means the element at the given startIndex will be included in the sublist but the element at the endIndex will not be.

The sublist returned from this method is backed by the original ArrayList object, so if you make any changes to the sublist, it will be reflected in the ArrayList, and vice versa.

Output

How to sort an ArrayList in Java?

The sort method of the ArrayList class sorts the ArrayList elements according to the specified Comparator.

The below given example shows how to sort an ArrayList of Integer in descending order using a Comparator and the sort method.

Output

Please visit sorting an ArrayList using a Comparator example for more details.

Tip: Instead of passing a reference of a Comparator object, you can also pass null to sort ArrayList elements in a natural order (i.e. ascending for the integer). Condition is, in this case, the elements in the ArrayList must implement the Comparable interface. It works for our example because the Integer class has implemented the Comparable interface.

Output

Apart from the sort method of the ArrayList class, you can also use the sort method of the Collections class to sort ArrayList elements.

Output

Similarly, you can use the custom Comparator to sort the ArrayList elements using an overloaded sort method of the Collections class.

Output

How to synchronize the ArrayList?

The ArrayList class is not a synchronized implementation. That means, if multiple threads are trying to modify the ArrayList structurally like adding or removing elements, the access must be synchronized to avoid unexpected results.

If your application is multi-threaded, you should get the synchronized list wrapper for the ArrayList using the synchronizedList method of the Collections class as given below.

This method returns a thread-safe (synchronized) List object backed by the original ArrayList. You should use this List object instead of the original ArrayList to make sure that the multi-threaded behavior of your application remains consistent.

How to get the intersection of two ArrayList objects using the retainAll method?

The retainAll method of the ArrayList class retains only elements that are also present in the specified another ArrayList or Collection object. All the elements that are not present in the specified another list will be removed from this ArrayList (thus creating an intersection of two ArrayList objects).

Output

How to check if the ArrayList contains all the elements of another ArrayList using the containsAll method?

The containsAll method returns true if this ArrayList object contains all the elements of the specified another ArrayList or Collection object. It returns false otherwise.

Output

Below given Java ArrayList examples will help you understand ArrayList concepts in more detail.

Java ArrayList Examples

ArrayList conversions examples

References:
ArrayList Javadoc

Please let me know if you liked the Java ArrayList tutorial with examples in the comments section below.

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

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