The ArrayList class in Java is a widely used data structure for storing dynamic data. It implements List interface that is a part of Java's Collection framework. Majority of developers favor ArrayList over the normal array by because of its flexibility to grow and shrink dynamically.

ArrayList vs Array

  • Unlike an array that has a fixed length, ArrayList is resizable. When a new element is added, it is extended automatically. Likewise, when an element is removed, it shrinks.There are no empty slots.
  • ArrayList uses an array internally to store the elements. So you can use zero-based index to randomly retrieve the elements.
  • Just like the array, you can store duplicate and null values in ArrayList.
  • ArrayList maintains the insertion order of the elements.
  • Unlike the array that can be of primitive type, you cannot use primitives like int, double, and char to create an ArrayList. You must use reference types like String, Integer or Double to create an ArrayList.

Creating an ArrayList

There are multiple ways to create an ArrayList:

// create an empty array list
List<String> list = new ArrayList<>();

// create and initialize array list
List<String> list2 = new ArrayList<>(Arrays.asList("🐭", "🐧", "πŸ¦…", "🐦"));

// create an array list with specified initial size
List<String> list3 = new ArrayList<>(10);

// Java 8 `Arrays.asList()` method (immutable)
List<Integer> list4 = Arrays.asList(1, 2, 3, 4, 5);

// Java 9 `List.of()` method (immutable)
List<Integer> list5 = List.of(1, 2, 3, 4, 5);

ArrayList Methods

The ArrayList class inherits a lot of methods from parent classes List, Collection and Iterable. However, the most used methods are set(), get(), size(), remove(), and isEmpty(). Here is a simple example of an ArrayList showing the use of these methods:

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

// add elments
list.add("🐭");
list.add("🐧");
list.add("πŸ¦…");
list.add("🐦");

// get items
list.get(0); // 🐭 
list.get(2); // πŸ¦…
        
// get elements count
list.size(); // 4

// update element at index 1
list.set(1, "πŸ¦„"); 
list.get(1); // πŸ¦„

// remove elements using value
list.remove("πŸ¦„"); // true

// remove elements using index
list.remove(0); // true

// check if list is empty
list.isEmpty(); // false

Iterating over ArrayList

You can iterate over the ArrayList elements through multiple methods:

// simple `for` loop
for (int i = 0; i < foods.size(); i++) {
    System.out.println(foods.get(i));
}

// for each loop
for (String item : foods) {
    System.out.println(item);
}

// Java 8 `forEach` from Streams API
foods.forEach(System.out::println);

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. β˜• Buy me a coffee (cost $3)

Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: hi@attacomsian.com.