August 29, 2022

Java ArrayList With Examples

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 a 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 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 and the existing elements are copied to this new array. 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 in Java

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 it 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 in the code those elements are printed too.

import java.util.ArrayList;
import java.util.List;

public class ArrayListDemo {
  public static void main(String[] args) {
    List<String> nameList = new ArrayList<String>();
    // adding elements
    nameList.add("Adam");
    nameList.add("Amy");
    nameList.add("Jim");
    // Adding at specific index
    nameList.add(0, "Leo");
    // Displaying list elements
    for(String name : nameList){
      System.out.println("Name- " + name);
    }
  }
}
Output
Name- Leo
Name- Adam
Name- Amy
Name- Jim

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

List<String> nameList = new ArrayList<String>();

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 a 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 times.

import java.util.ArrayList;
import java.util.List;

public class ArrayListDemo {
  public static void main(String[] args) {
    List<String> nameList = new ArrayList<String>();
    // adding elements
    nameList.add("Adam");
    nameList.add("Amy");
    nameList.add(null);
    nameList.add("Jim");
    nameList.add("Jim");
    nameList.add(null);
    // Displaying list elements
    for(String name : nameList){
      System.out.println("Name- " + name);
    }
    System.out.println("Size of the list- " + nameList.size());
  }
}
Output
Name- Adam
Name- Amy
Name- null
Name- Jim
Name- Jim
Name- null
Size of the list- 6

Java example to remove elements from an ArrayList

Following example shows how you can delete any element from a Java ArrayList using remove() method.

public class ArrayListDemo {
  public static void main(String[] args) {
    List<String> nameList = new ArrayList<String>();
    // adding elements
    nameList.add("Adam");
    nameList.add("Amy");
    nameList.add("Jim");
    nameList.add("Leo");
    // removing using index
    nameList.remove(2);
    // Displaying list elements
    for(String name : nameList){
      System.out.println("Name- " + name);
    }
    System.out.println("--------------------------");
    // removing using object
    nameList.remove("Leo");
    // Displaying list elements
    for(String name : nameList){
      System.out.println("Name- " + name);
    }
  }
}
Output
Name- Adam
Name- Amy
Name- Leo
--------------------------
Name- Adam
Name- Amy

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.

If you want to add int to an ArrayList-

public class ArrayListDemo {
  public static void main(String[] args) {
    List<Integer> numList = new ArrayList<Integer>();
    // Wrapping int in Integer wrapper class
    numList.add(new Integer(5));
    // Done automatically
    numList.add(6);
    for(Integer num : numList){
      System.out.println("Number- " + num);
    }
  }	
}
Output
Number- 5
Number- 6

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.

Java 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 How to Iterate Java ArrayList 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
public class ArrayListDemo {
  public static void main(String[] args) {
    List<String> nameList = new ArrayList<String>();
    // adding elements
    nameList.add("Adam");
    nameList.add("Amy");
    nameList.add("Jim");
    nameList.add("Leo");
    // getting iterator
    Iterator<String> itr = nameList.iterator();
    while(itr.hasNext()){
      System.out.println("Name- " + itr.next());
      nameList.add("Jack");			
    }
  }
}
Output
Name- Adam
Exception in thread "main" java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
	at java.util.ArrayList$Itr.next(Unknown Source)
	at com.knpcode.ArrayListDemo.main(ArrayListDemo.java:20)

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
public class ArrayListDemo {
  public static void main(String[] args) {
    List<String> nameList = new ArrayList<String>();
    // adding elements
    nameList.add("Adam");
    nameList.add("Amy");
    nameList.add("Jim");
    nameList.add("Leo");
    // getting iterator
    Iterator<String> itr = nameList.iterator();
    while(itr.hasNext()){
      String name = itr.next();
      if(name.equals("Jim")){
        // using iterators remove method
        itr.remove();
      }	
    }
    for(String name : nameList){
      System.out.println("Name- " + name);
    }
  }
}
Output
Name- Adam
Name- Amy
Name- Leo

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 using Collections.synchronizedList() method. For example-

List<String> tempList = Collections.synchronizedList(nameList);

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 Java ArrayList With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment