Introduction to the Java ArrayList

Updated on December 23rd, 2018

In this post, we will cover features of Java ArrayList class. We will discuss its features and well-known use cases.

 

Java ArrayList

The ArrayList class is the part of Java Collection Framework. This class implements the List interface provided by the Collection framework. This is a high level hierarchy for the Array list

ArrayList

Here are features or key points about the ArrayList in Java:

  1. The ArrayList grow and sink dynamically when we add/remove elements from it.
  2. ArrayList use the array as an internal data structure to store element.
  3. This provides flexibility to use elements using the indexes.
  4. ArrayList allows to store duplicate values including “null” values.
  5. It is an ordered collection i.e. it maintains the insertion order.
  6. Java ArrayList supports Generics.
  7. It only allows objects in the ArrayList. For primitives values like int, long etc. use the wrapper classes.
  8. Java ArrayList Iterator and ListIterator implementation is fail-fast.
  9. ArrayList is not thread safe. We need to apply synchronization if multiple threads will change ArrayList at the same time.

Here are known parameters for the Java ArrayList complexity.

  • Add operation has O(1) complexity.
  • Remove has O(1) complexity.
  • Contains operation have O(n) complexity.

Internally ArrayList is a resizable-array implementation of the List interface. Here is a sample code with ArrayList

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

public class ArrayListExample {

 public static void main(String[] args) {

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

  //Add operation
  list.add("California");
  list.add("Alabama");
  list.add("Colorado");
  list.add("Delaware");
  list.add(4, "Texas"); //add based on index

  list.contains("Virginia"); //false

  list.remove("Colorado");
  list.remove(1); //remove by index
 }
}

Let’s inspect the ArrayList

 

1. ArrayList Creation

On a high level, we have the following way to create a new ArrayList in Java.

  • Use a default constructor.
  • Pass initial capacity in the constructor.
  • Pass Java Collection as a constructor parameter.

 

1.1 Default Constructor

This is one of the most common ways to create ArrayList in Java. We are creating an empty ArrayList.

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

 

1.2  Constructor with Initial Capacity

This option allows us to construct an empty list with the specified initial capacity. This is helpful to avoid frequent resizing during the add operation

List<String> list= new ArrayList<String>(10);

 

1.3  Constructor with Collection

This method helps to Constructs a list containing the elements of the specified collection.

List<String> intialList = Arrays.asList("California","Alabama");
List<String> list= new ArrayList<String>(intialList)

While creating ArrayList, we should keep in mind following extra points.

  • ArrayList is generic, and it’s always recommended to pass element type to let compiler make sure data integrity.
  • ArrayList implements List interface, and it’s a good practice to use generic interface for better decoupling.

 

2. Add Elements

We can add elements by calling add() method or if required we can add an element at the specified position using index property. 

List<String> list= new ArrayList<String>();
list.add("California");
list.add(4,"Texas");

We can also add multiple elements at once.

List<String> intialList = Arrays.asList("California1","Alabama1");
List<String> list= new ArrayList<String>();
list.addAll(intialList);

 

2.1 Creating an ArrayList and adding elements

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

public class ArrayListExample {

 public static void main(String[] args) {
  // Creating an ArrayList of String
  List < String > states = new ArrayList < > ();

  // Adding new elements to the ArrayList
  states.add("California");
  states.add("Alabama");
  states.add("Florida");
  states.add("Hawaii");
  states.add("New York");

  System.out.println(states);

  // Adding an element at a particular index in an ArrayList
  states.add(3, "Texas");

  System.out.println(states);

 }
}
#Output
[California, Alabama, Florida, Hawaii, New York]
[California, Alabama, Florida, Texas, Hawaii, New York]

 

2.2 Creating an ArrayList from Collection

There are two options to create an ArrayList from another collection.

  1. Use the ArrayList​(Collection<? extends E> c) constructor to pass the collection as a parameter.
  2.  Use addAll​(Collection<? extends E> c) method to append all the elements in the specified collection to the end of this list.
public class ArrayListExample {

 public static void main(String[] args) {
  // Creating an ArrayList of String
  List < String > states = new ArrayList < > ();

  // Adding new elements to the ArrayList
  states.add("California");
  states.add("Alabama");
  states.add("Florida");
  states.add("Hawaii");
  states.add("New York");

  // Creating an ArrayList from another collection
  List < String > newStateList = new ArrayList < > (states);
  System.out.println(newStateList);

  List < String > additionalStates = new ArrayList < > ();
  additionalStates.add("Washington");
  additionalStates.add("Wisconsin");
  additionalStates.add("Missouri");

  // Adding an entire collection to an ArrayList
  newStateList.addAll(additionalStates);

  System.out.println(newStateList);

 }
}
#Output
[California, Alabama, Florida, Hawaii, New York]
[California, Alabama, Florida, Hawaii, New York, Washington, Wisconsin, Missouri]

 

3. Remove Elements

There are two variations of the remove operation in ArrayList.

  • Use remove() method to remove an element by value or using an index.remove() by Object will remove the first occurrence of the specified element from this list.
  • Use removeAll() to remove from this list all of its elements that are contained in the specified collection.
List < String > list = new ArrayList < String > ();
list.addAll(intialList);
//Add operation
list.add("California");
list.add("Alabama");
list.add("Colorado");
list.add("Delaware");

list.remove("Colorado"); //By value
list.remove(1); //remove by index

List < String > removeCollection = Arrays.asList("California", "Alabama");
list.removeAll(removeCollection);

 

4. Iterate ArrayList Elements

We have two different ways to iterate elements of the Java ArrayList.

  • Iterator – Provide option to iterate a list in one direction.
  • Listiterator – An iterator for lists that allows the programmer to traverse the list in either direction
List < Integer > integerList = Arrays.asList(1, 2, 3, 6, 7, 4, 9, 11, 34, 12, 22);
 ListIterator < Integer > listIterator = integerList.listIterator();
 while (listIterator.hasNext()) {
  System.out.println("Next element is " + listIterator.next());
 }
 while (listIterator.hasPrevious()) {
  System.out.println("Previous element is " + listIterator.previous());
 }

Java 8 brought several fundamental changes to the API. Use forEach() method directly in the list to performs the action for each element of the Iterable until it has processed all elements or the action throws an exception.

 

5. Search

ArrayList provides several options to search elements through the list.

  • Use indexOf() and lastIndexOf() methods to get index element for the method.
  • contains(Object) – Returns true if this list contains the specified element.
List < String > stringList = Arrays.asList("California", "Alabama", "Colorado", "Delaware", "Virginia");
assertEquals(1, stringList.indexOf("Alabama"));

If your code requires the frequent check for specific elements, better to use a HashSet than an ArrayList. Java doc for HashSet says: “This class offers constant time performance for the basic operations (add, remove, contains and size)”

 

6. Access Elements from ArrayList

The ArrayList provides following methods to access its values or state:

  • Use the size() method to find the size of ArrayList.
  • The Get() method provides the element at a particular index in an ArrayList.
  • Use the set() method to change or set element at a particular index.
  • The isEmpty() method to check if ArrayList is empty.
import java.util.ArrayList;
import java.util.List;

public class ArrayListExample {

    public static void main(String[] args) {
        // Creating an ArrayList of String
        List states = new ArrayList<>();
        System.out.println("Is State list is empty: "+states.isEmpty());
        
        // Adding new elements to the ArrayList
        states.add("California");
        states.add("Alabama");
        states.add("Florida");
        states.add("Hawaii");
        states.add("New York");

        
        System.out.println("Number of states in our ArrayList is: "+states.size());
        System.out.println("First State in our list is: "+states.get(0));
        
        //let's modify out list
        states.set(0,"Alaska ");
        System.out.println("New first State in our list is: "+states.get(0));
    }
}
#Output:
Is State list is empty: true
Number of states in our ArrayList is: 5
First State in our list is: California
New first State in our list is: Alaska 

 

Summary

In this post, we discussed the ArrayList in Java. We learned how to create a new ArrayList in Java and how to do different operations on the ArrayList.

Java Development Journal

Hello!! Welcome to the Java Development Journal. We love to share our knowledge with our readers and love to build a thriving community.

follow me on:

Leave a Reply

avatar

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

  Subscribe  
Notify of