Home Java ArrayList in Java with examples

ArrayList in Java with examples

ArrayList in java is similar to an array, except that there is no size limit in the ArrayList. ArrayList is dynamic hence allows adding and removing of elements anytime. Though, the elements in an ArrayList are stored in the order of insertion. An ArrayList is not synchronized and can also store objects that include null values.

Hierachical Diagram for Java ArrayList
Hierachical Diagram for Java ArrayList

ArrayList is the implementation of the list Interface found in java.util package. The List extends the Collections Interface, which intern extends the Iterable Interface.
An interface is a collection of abstract methods. You cannot create instances of an abstract method.

Prerequisite

To get a clear understanding of ArrayList, it will be of great advantage to first understand Arrays. Know the difference between the one-dimension and the two-dimension arrays, know how to create, access, add items, remove and also loop through the array items. Suppose you don’t have this knowledge, though, you don’t have to panic as we will make this tutorial as simple as possible, even for beginners. Let’s dig into ArrayList in java.

Features of Java ArrayList

  • ArrayList uses an index-based structure in java.
  • An ArrayList can store duplicate elements.
  • ArrayList is resizable; hence you can decrease and increase its size.
  • An ArrayList is not synchronized.
  • It has a random access property since we can get, set, remove and insert elements of the array from any arbitrary position.
  • It’s possible to add null elements in an ArrayList.
  • Elements are sorted in the order of insertion.
  • Its performance is slow due to a lot of shifting when you remove an element from an ArrayList.

Difference between an Array and an ArrayList

In an array, its size cannot be modified, and that means if you may wish to add or remove elements from the array, you must create a new one. In an ArrayList, its size is resizable; hence you can add and remove elements any moment you wish.

Creating an ArrayList

The first point to note is that every time you need to you create an arrayList you must first the java.util.arrayList package.
Exampe:

import java.util.ArrayList;

Let’s now create an ArrayList of objects called Laptops that will store Strings of names of laptop brands.

package javaarraylist;
import java.util.ArrayList;
public class JavaArrayList {
    public static void main(String[] args) 
    {
     ArrayList <String> laptops = new ArrayList <String>();
    }   
}

In the above example, the ArrayList holds laptop objects of type String, a non-primitive type. We can also create an ArrayList to hold other primitive types of objects such as Integer, Boolean, Character, and double.
Example:

package javaarraylist;
import java.util.ArrayList;
public class JavaArrayList {
    public static void main(String[] args) 
    {
     ArrayList <Character> A = new ArrayList <Character>();
     ArrayList <Integer> numbers = new ArrayList <Integer>();
     ArrayList <Double> doubleArrayList = new ArrayList <Double>();
    }
}

The advantage of specifying the type such as a String or an Integer is, in case you try to add another type, it gives a compile-time error. Below is another method of creating an ArrayList using two lines.

package javaarraylist;
import java.util.ArrayList;
public class JavaArrayList {
    public static void main(String[] args) 
    {
     ArrayList <String> laptops;
      
      Laptops= new ArrayList <String>();
    }   
}

How to Initialize an ArrayList

There are three methods that we can use to initialize an ArrayList in Java.

The normal way of Initialization

package javaarraylist;
import java.util.ArrayList;
public class JavaArrayList {
    public static void main(String[] args) 
    {
     ArrayList <String>Laptops= new ArrayList <String>(); 
  	Laptops.add("Laptops o1");
 	Laptops.add("Laptops o2");

    }   
}

Arrays.asList  initialization

package javaarraylist;
import java.util.ArrayList;
public class JavaArrayList {
    public static void main(String[] args) 
    {
     ArrayList <String>Laptops= new ArrayList <String>(Arrays.asList("A", "B", "C")); 
  	      }   
}

Anonymous Inner Class Initialization

package javaarraylist;
import java.util.ArrayList;
public class JavaArrayList {
    public static void main(String[] args) 
    {
     ArrayList <String>Laptops= new ArrayList <String>(){{   
  	 	add(Laptops o1);
   		add(Laptops o2);
   		add(Laptops o3);
 
 }};

  	      }   
}

ArrayList Methods/Operations

Add Items in the ArrarList

We add items to an ArrayList using the add() method.
Example:

package javaarraylist;
import java.util.ArrayList;
public class JavaArrayList {
    public static void main(String[] args) 
    {
     ArrayList <String> Laptops = new ArrayList <String>();
     Laptops.add("Dell");
     Laptops.add("Hp");
     Laptops.add("Lenovo");
     
    System.out.println("======String Objects==========");
    System.out.println(Laptops);
    
     ArrayList <Character> A = new ArrayList <Character>();
     A.add('a');
     A.add('b');
     A.add('c');
     A.add('d');
     
    System.out.println("======Character Objects==========");
    System.out.println(A);
     
     ArrayList <Integer> numbers = new ArrayList <Integer>();
     numbers.add(1);
     numbers.add(2);
     numbers.add(3);
    
    System.out.println("======Integer Objects==========");
    System.out.println(numbers);
    
     ArrayList <Double> doubleArrayList = new ArrayList <Double>();
     doubleArrayList.add(12.12);
     doubleArrayList.add(12.23);
     doubleArrayList.add(10.10);
    
    System.out.println("======Double Objects==========");
    System.out.println(doubleArrayList);    
    }
}

From the above examples, you will also note how to define the different types of objects. Strings are enclosed between the double (“”), the character between single quotes (”), but Integers and double quotes are not enclosed in any quotes.
Output:

run:
======String Objects==========
[Dell, Hp, Lenovo]
======Character Objects==========
[a, b, c, d]
======Integer Objects==========
[1, 2, 3]
======Double Objects==========
[12.12, 12.23, 10.1]
BUILD SUCCESSFUL (total time: 0 seconds)

We can also add an item in the ArrayList while specifying the index in the add method.

ArrayList <String> Laptops = new ArrayList <String>();
Laptops.add(3,"Toshiba");

From the above code, it will add “Toshiba” at the fourth position. Rememer our index starts at 0.

Access Items in the ArrayList

If we were accessing elements from an array, we call the array name and the index of the array we need. print ( my_array [ 0 ] ). In an ArrayList, we use a method called get(). Its index also starts from 0.
For example, if we want to access the third item from our laptops, ArrayList. We print.
System.out.println(Laptops.get(2));

package javaarraylist;
import java.util.ArrayList;
public class JavaArrayList {
    public static void main(String[] args) 
    {
     ArrayList <String> Laptops = new ArrayList <String>();
     Laptops.add("Dell");
     Laptops.add("Hp");
     Laptops.add("Lenovo");
     Laptops.add("Toshiba");   
    
    System.out.println(Laptops.get(2));
    }
}

Output

run:
Lenovo
BUILD SUCCESSFUL (total time: 0 seconds)

Changing an Item In the ArrayList

When we want to modify an ArrayList element, we use the set() method. It holds two Items, one being the index of the value you want to modify, and the second one is the value you want to modify with.
Let’s modify Lenovo to Acer and print the modified element from our list.

package javaarraylist;
import java.util.ArrayList;
public class JavaArrayList {
    public static void main(String[] args) 
    {
     ArrayList <String> Laptops = new ArrayList <String>();
     Laptops.add("Dell");
     Laptops.add("Hp");
     Laptops.add("Lenovo");
     Laptops.add("Toshiba");
     
    Laptops.set(2, "Acer");
    System.out.println(Laptops.get(2));
    }
}

Output:

run:
Acer
BUILD SUCCESSFUL (total time: 0 seconds)

Removing Items in the ArrayList

You can either remove a single element from an ArrayList using the index and the remove() or remove all the elements from the ArrayList using clear() method.

package javaarraylist;
import java.util.ArrayList;
public class JavaArrayList {
    public static void main(String[] args) 
    {
     ArrayList <String> Laptops = new ArrayList <String>();
     Laptops.add("Dell");
     Laptops.add("Hp");
     Laptops.add("Lenovo");
     Laptops.add("Toshiba");
     
    Laptops.remove(2);
    System.out.println(Laptops);
    
    Laptops.clear();
    System.out.println(Laptops);
    }
}

Output:

run:
[Dell, Hp, Toshiba]
[]
BUILD SUCCESSFUL (total time: 0 seconds)

In the second part, it prints an empty ArrayList since all its objects have been removed.

Clone Method

The clone() method copies and returns the exact copy of ArrayList objects.
Example:

package javaarraylist;
import java.util.ArrayList;
public class JavaArrayList {
    public static void main(String[] args) 
    {
     ArrayList <String> Laptops = new ArrayList <String>();
     Laptops.add("Dell");
     Laptops.add("Hp");
     Laptops.add("Lenovo");
     Laptops.add("Toshiba");
     
    System.out.println(Laptops);
    
     ArrayList <String> LaptopsCopy =(ArrayList <String>)Laptops.clone();
    
    System.out.println("====printing the copied Items======");
    
    System.out.println(LaptopsCopy);
        
    }
}

Output

run:
[Dell, Hp, Lenovo, Toshiba]
====printing the copied Items======
[Dell, Hp, Lenovo, Toshiba]
BUILD SUCCESSFUL (total time: 0 seconds)

How to determine the size of an ArrayList

To determine the size of an array, we use the size() method.
Example:

package javaarraylist;
import java.util.ArrayList;
public class JavaArrayList {
    public static void main(String[] args) 
    {
     ArrayList <String> Laptops = new ArrayList <String>();
     Laptops.add("Dell");
     Laptops.add("Hp");
     Laptops.add("Lenovo");
     Laptops.add("Toshiba");
     
    System.out.println("Printing the size of the array");
    System.out.println(Laptops.size());
    
    }
}

Output:

run:
Printing the size of the array
4
BUILD SUCCESSFUL (total time: 0 seconds)

Loop through an ArrayList

There are two ways to loop through an ArrayList.

For-loop

To specify the number of times to loop through you can use size() method.

package javaarraylist;
import java.util.ArrayList;
public class JavaArrayList {
    public static void main(String[] args) 
    {
     ArrayList <String> Laptops = new ArrayList <String>();
     Laptops.add("Dell");
     Laptops.add("Hp");
     Laptops.add("Lenovo");
     Laptops.add("Toshiba");
     
     for (int i = 0; i < Laptops.size(); i++) {
      System.out.println(Laptops.get(i));
    }
    
    }
}

Output:

run:
Dell
Hp
Lenovo
Toshiba
BUILD SUCCESSFUL (total time: 1 second)

For-each loop (iterator)

The second method is using for-each loop or called iterator loop.

package javaarraylist;
import java.util.ArrayList;
public class JavaArrayList {
    public static void main(String[] args) 
    {
     ArrayList <String> Laptops = new ArrayList <String>();
     Laptops.add("Dell");
     Laptops.add("Hp");
     Laptops.add("Lenovo");
     Laptops.add("Toshiba");
     
   for (String i : Laptops) {
      System.out.println(i);
    }
    }
}

There are other looping methods through the ArrayList, like using the Lamba. Let’s view this through a code for better understanding.

package javaarraylist;

import java.util.ArrayList;
import java.util.function.Consumer;

public class JavaArrayList {

    public static void main(String[] args) 
    {
        // Creating an array list
        ArrayList<String> Laptops = new ArrayList<>();

        // Insert some elements
     Laptops.add("Dell");
     Laptops.add("Hp");
     Laptops.add("Lenovo");
     Laptops.add("Toshiba");
       System.out.println( "======Iterate using standard for loop=====");
        for (int i=0; i<Laptops.size(); i++) {
            System.out.println(Laptops);
        }
        
        System.out.println("==== Iterate using an iterator====");
        for (String i : Laptops) {
      System.out.println(i);
    }
        
        System.out.println("===Iterate using ArrayList.forEach====");
        Laptops.forEach(new Consumer<String>() {
            @Override
            public void accept(String i) {
                System.out.println(i);
            }
        });
        
       System.out.println("===== Iterate using forEach and Lambda=====");
        Laptops.forEach(i -> System.out.println(i));

       System.out.println("=====Iterate using forEach and method reference======");
        Laptops.forEach(System.out::println);

    }
}

Output:

run:
======Iterate using standard for loop=====
[Dell, Hp, Lenovo, Toshiba]
[Dell, Hp, Lenovo, Toshiba]
[Dell, Hp, Lenovo, Toshiba]
[Dell, Hp, Lenovo, Toshiba]
==== Iterate using an iterator====
Dell
Hp
Lenovo
Toshiba
===Iterate using ArrayList.forEach====
Dell
Hp
Lenovo
Toshiba
===== Iterate using forEach and Lambda=====
Dell
Hp
Lenovo
Toshiba
=====Iterate using forEach and method reference======
Dell
Hp
Lenovo
Toshiba
BUILD SUCCESSFUL (total time: 0 seconds)

Sort an ArrayList

The sort() method is used to sort the ArrayList elements. You can use either sort in Ascending order or in Descending order. We need to import the collections package for the sort to work out.

Import java.utils.collections

Example:

package javaarraylist;

import java.util.ArrayList;
import java.util.Collections;

public class JavaArrayList {

    public static void main(String[] args) 
    {
        ArrayList <String> Laptops = new ArrayList <String>();
     Laptops.add("Dell");
     Laptops.add("Acer");
     Laptops.add("Lenovo");
     Laptops.add("Toshiba");
     
     System.out.println("===unsorted list==");
     System.out.println(Laptops);
     
    System.out.println("===sorted list=="); 
    Collections.sort(Laptops);
    System.out.println(Laptops);
    }

}

Output:

run:
===unsorted list==
[Dell, Acer, Lenovo, Toshiba]
===sorted list==
[Acer, Dell, Lenovo, Toshiba]
BUILD SUCCESSFUL (total time: 0 seconds)

ArrayList Constructors

ArryList()

This constructor is used to create an empty ArrayList. The initial capacity of this default ArrayList is 10.

ArrayList emptylist = new ArrayList(); 

ArrayList(Collection c)

We can create and initialize a collection of elements to an ArrayList using this constructor.

ArrayList <String> Laptops = new ArrayList<String>(list); 
//list specifiesa collection of elements

ArrayList(int capacity)

To build an ArrayList with initial capacity being specified at the initialization time, we can use this constructor.
Let’s take an example, suppose we need to add 600 elements in an ArrayList, we will create the ArrayList to initialize it to hold the 600 elements.

ArrayList<Integer> capacity = new ArrayList<Integer>(600);

How to increase and decrease the size of an ArrayList

As we had mentioned earlier, an ArrayList is dynamic, but we can also increase and decrease its size manually using two methods.

EnsureCapacity();

ArrayList<String>Laptops = new ArrayList<String>();
  Laptops.ensureCapacity(20);

This method increases the current capacity of the ArrayList. In the example above, the default size of the ArrayList is 10, but it increases to 20 by use of the ensureCapacity() method.

Trim Tosize();

ArrayList<String>Laptops = new ArrayList<String>();
  Laptops.ensureCapacity(20);

Laptopsl.trimTosize();

After Increasing the array’s size to hold 20 elements, the trimTosize() method reduces it back to its default size.

How to compare two ArrayList in Java

To compare two ArrayList in Java we use the contains() method.

package javaarraylist;

import java.util.ArrayList;
import java.util.Collections;

public class JavaArrayList {

    public static void main(String[] args) 
    {
       ArrayList<String> Laptops1= new ArrayList<String>();
          Laptops1.add("Dell");
          Laptops1.add("Lenovo");
          Laptops1.add("Toshiba");
          Laptops1.add("Acer");
          Laptops1.add("Acer");

          ArrayList<String> Laptops2= new ArrayList<String>();
          Laptops2.add("IBM");
          Laptops2.add("Thinkpad");
          Laptops2.add("Acer");
          Laptops2.add("Acer");

          //Storing the comparison output in ArrayList<String>
          ArrayList<String> Comparison= new ArrayList<String>();
          for (String temp : Laptops1)
              Comparison.add(Laptops2.contains(temp) ? "Yes" : "No");
          System.out.println(Comparison);

    }

}

We first created two ArrayList to hold String of object type laptops and then created the last ArrayList to compare the two ArrayList and return ‘yes’ if they are the same and ‘no’ if they are not the same.

Output:

run:
[No, No, No, Yes, Yes]
BUILD SUCCESSFUL (total time: 1 second)

Conclusion

This tutorial covered the most important points one should understand to start working with Java ArrayList. You learned how to create, add, access, sort, loop, remove, compare, and construct. In conclusion, we can also say that an Arraylist is the implementation of a dynamic/resizable array. Please leave feedback in the comment section in case of any questions. I will be glad to help!

You may also like

1 comment

Kangogo Joel January 28, 2021 - 4:34 pm

Well detailed, thumbs up!

Reply

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More