ArrayList in Java

In Java programming language when you create an array you will have to provide its length. Once created array is of fixed length and that length can’t be changed. In many cases you may not know the exact length in advanced in such scenarios you can use ArrayList in Java.

ArrayList class in Java

ArrayList in Java is resizable-array implementation of the List interface and resides in java.util package. Since ArrayList is dynamic so it can grow or shrink automatically.

Internally ArrayList also uses an array which is created with an initial capacity. If that capacity is reached because of the addition of elements, a new array is created whose capacity is 50% more than the capacity of the older one. Same way when an element is removed from an ArrayList the gap created in the underlying array is filled automatically. As a user that logic of increasing or decreasing the length of an ArrayList is abstracted from us.

Refer ArrayList Internal Implementation in Java to know more about internal implementation of ArrayList in Java.

Features of ArrayList

Some of the features of the ArrayList which are discussed in this post are as follows-

  1. ArrayList is part of Java Collections framework. ArrayList extends AbstractList class and implements List, RandomAceess, Cloneable and Serializable interfaces.
  2. While creating an ArrayList you can provide the capacity for the ArrayList or use the default capacity which is 10.
  3. Since ArrayList in Java implements RandomAccess interface so elements of the list can be accessed randomly by passing the index of the element with the method. Index starts at 0 in List.
  4. ArrayList in Java can store only objects, if you need to store primitive data types you will have to use wrapper classes. Because of Autoboxing even that can happen automatically where primitives are wrapped behind the scene.
  5. You can add null to an ArrayList.
  6. Adding duplicate elements to an ArrayList is also allowed.
  7. ArrayList in Java is not thread safe.
  8. The iterators returned by iterator and listIterator methods of ArrayList are fail-fast. Which means, if the list is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove or add methods, the iterator will throw a ConcurrentModificationException.

Java ArrayList Constructors

  • ArrayList()– This constructor creates an empty list with an initial capacity of ten, which is the default capacity.
  • ArrayList(int initialCapacity)– This constructor constructs an empty list with the specified initial capacity.
  • ArrayList(Collection<? extends E> c)– Constructs a list containing the elements of the specified collection, in the order they are returned by the collection’s iterator.

Java example creating an ArrayList

Let’s see an example where an ArrayList is created and elements are added to it. Later those elements will also be printed.

Output

As you can see an ArrayList of default capacity is created using this statement.

All Collections classes are generic now, so you can specify in the beginning itself what type of elements will be stored in the list. The list used in this example can store only Strings.

Then some elements are added to the list, one of the element is added at a specific index. Later the elements are displayed using for-each loop.

Methods in the ArrayList class

Here is the list of some of the methods in the ArrayList class in java.

  1. add(int index, E element)– This method inserts the passed element at the specified position in this list.
  2. add(E e)– This method appends the specified element to the end of this list.
  3. addAll(int index, Collection<? extends E> c)– This method inserts all of the elements in the passed collection into this list, starting at the specified position.
  4. addAll(Collection<? extends E> c)– This method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s Iterator.
  5. clear()– Method to remove all of the elements from this list.
  6. contains(Object o)– Returns true if this list contains the specified element.
  7. get(int index)– Returns the element at the specified position in this list.
  8. indexOf(Object o)– Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
  9. isEmpty()– Returns true if this list contains no elements.
  10. iterator()– Returns an iterator over the elements in this list in proper sequence.
  11. lastIndexOf(Object o)– Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.
  12. remove(int index)– Removes the element at the specified position in this list.
  13. remove(Object o)– Removes the first occurrence of the specified element from this list, if it is present.
  14. removeIf(Predicate<? super E> filter)– Removes all of the elements of this collection that satisfy the given predicate.
  15. set(int index, E element)– Replaces the element at the specified position in this list with the specified element.
  16. size()– Returns the number of elements in this list.

ArrayList allows duplicate values and null

In ArrayList you can add duplicate elements, null is also allowed that too any number of time.

Example code

Output

Example code to remove elements from an ArrayList

Output

Adding primitive data types to an ArrayList

ArrayList in Java can store only objects, if you need to store primitive data types you will have to wrap them in the corresponding wrapper class to get an object. With autoboxing even that process is automatic now and done behind the scene.

Example code

If you want to add int to an ArrayList-

Output

In the code you can see both of the ways to add the primitive data types to an ArrayList. While adding first element int is wrapped in the Integer wrapper class. In the second addition it is done automatically.
Also notice in the for-each loop you are assigning the elements to an Integer variable which doesn’t create any problem for the second element as it is automatically wrapped to get an Integer object.

ArrayList iterator

Using iterator in ArrayList you can traverse the list in a sequential manner. You can get an Iterator using iterator() method and ListIterator using listIterator() method. Difference between Iterator and ListIterator is that ListIterator allows to traverse the list in either direction.

Refer Different Ways to Iterate an ArrayList in Java to see different options to iterate an ArrayList in Java.

The iterators returned by both iterator and listIterator methods are fail-fast. If the list is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove or add methods, the iterator will throw a ConcurrentModificationException. Note that List iterator provides both add and remove methods where as Iterator interface provides only remove() method.

Java ArrayList iterator example

Output

In the code while iteration is in progress an attempt is made to add an element using the list’s add method (Structural modification) that is why ConcurrentModificationException is thrown.

Example code using iterator’s remove method

Output

This code works fine as the modification is done using the iterator’s remove method.

ArrayList is not thread-safe

ArrayList in Java is not thread safe. If an instance of ArrayList is shared among multiple threads and any thread modifies the List structurally then other threads may not get the updated list. In such scenario ArrayList must be synchronized externally. In order to synchronize an ArrayList you can use Collections.synchronizedList() method.

As example-

To see an example of how to synchronize ArrayList and what other thread-safe alternatives are available, refer this post- How to Synchronize ArrayList in Java

That’s all for the topic ArrayList in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.