An array is a widespread and essential data structure in every programming language with one disadvantage – its size is fixed. Let’s see how ArrayList in Java can help with this.

An array can be of two types: a static array or a dynamic array. An array cannot be increased dynamically in programming languages like Java. Instead, the size of the array is declared during the array initialization. But, in many cases, this can lead to many issues. To solve this issue, ArrayLists are used in Java. The array size increases automatically when an element is pushed to an ArrayList.

In this article, you’ll learn about ArrayLists in Java. You’ll understand the core difference between Array and ArrayList and also learn about the different types of ArrayLists and how to use them.

Array vs. ArrayList

The primary difference between an Array and an ArrayList is that the size of an Array is static, but an ArrayList size can be dynamic. As an Array is fixed, the time to iterate over the array takes less time than a dynamic array.

There are also a few more differences between them.

  • A static array can be single or multidimensional, but an ArrayList can only be single-dimensional.
  • An Array is a primitive data structure available in Java. But an ArrayList is a part of a Collection Framework API in Java. It is built on top of Arrays.
  • You can declare Arrays with primitive data types. Primitive data types cannot be used in an ArrayList. If you want to use a primitive data type, you’ll need to use the data type’s corresponding wrapper class.

Types of ArrayLists in Java

ArrayLists can be of any type. But you’ll need to pass the corresponding wrapper class because you cannot pass primitive data types in an ArrayList.

You can add simple data types like integer or string types by passing wrapper classes like Integer or String.

You can also pass in complex types like ArrayLists of ArrayLists, hashmaps, etc.

Let’s take a look at an example of using a custom class inside an ArrayList.

import java.util.ArrayList;

class User {
  private String name;
  private int age;

  public User(String name, int age) {
    this.name = name;
    this.age = age;
  }

  public void getUser() {
    System.out.println("Name: "   name   " Age: "   age);
  }
}

class Main {
    public static void main(String[] args) {
    ArrayList users = new ArrayList();

    users.add(new User("Subha", 25));
    users.add(new User("Dan", 32));

    users.forEach(user -> {
      user.getUser();
    });
  }
}

Output:
Name: Subha Age: 25
Name: Dan Age: 32

In the above code sample, an ArrayList of type User is created. You’ll learn more about the methods used in the example below.

Creating an ArrayList in Java

You have already understood the basics of an ArrayList in Java. Now let’s take a look at the syntax of an ArrayList, and following that, we’ll also see how it can be used in Java code.

ArrayList listName = new ArrayList();

The above snippet shows the syntax of defining an ArrayList. The Type defines the type of the ArrayList. For example, if you want to declare an ArrayList of integer data types, you can pass in . Note that you cannot pass int as it is a primitive data type.

You’ll also need to import the java.util.ArrayList to use ArrayList in your programs. Here’s a basic example of a program declaring an ArrayList:

import java.util.ArrayList;

class Main {
  public static void main(String[] args) {

    // Declare An ArrayList
    ArrayList rainbow = new ArrayList();

    System.out.println(rainbow); 
  }
}

Output:
[]

In the above code, an ArrayList named rainbow of type String is declared.

To work with the ArrayList, there are multiple methods available. Let’s take a look at a few methods.

The add Method

The ArrayList class provides various methods for performing operations like adding or removing elements, getting values, setting a value at a specific position, clearing an ArrayList, etc.

The first method we’ll see is the add method.

The add method is used for adding a single item to an ArrayList. The syntax for add is shown below.

arrayList.add(int i, Element) 

Let’s understand the syntax now. The first parameter i is an optional parameter representing the index position where the item you want to add. The second parameter Element is the element you want to add. Let’s take a look at an example now.

rainbow.add("Violet");
System.out.println(rainbow); 

Output:
[Violet]



rainbow.add(0, "Red");
System.out.println(rainbow); 

Output:
[Red, Violet]

The rainbow.add("Violet") adds an element to the end of an ArrayList. And the rainbow.add(0, "Red") adds the element Red to the index position 0 of the ArrayList. The add() method returns true when an item is successfully inserted.

The get Method

The get method is used to get the value from a specified position from an ArrayList.

arrayList.get(int i);

The i shown in the above syntax is the index position. For example, if you want to get the item from the index position 1, write arrayList.get(1).

rainbow.add("Violet");
rainbow.add(0, "Red");

String color = rainbow.get(1);
System.out.println(color); 


Output: 
Violet

The above code will return Violet from the ArrayList rainbow.

The set Method

The set method is used to replace an item’s value. For example, if you want to replace the value of an item at the index position 0, you write rainbow.set(0, "Purple"), assuming that you have an ArrayList called rainbow.

The syntax for the set method is as follows,

arrayList.set(int i, Element);

Where i is the index position, and Element is the value of the new element.

rainbow.add("Violet");
System.out.println(rainbow); 

Output:
[Violet]

rainbow.add(0, "Red");
System.out.println(rainbow);

Output:
[Red, Violet]

rainbow.set(1, "Purple");
System.out.println(rainbow);

Output:
[Red, Purple]

In the above example, we add two values to an ArrayList called rainbow. First, the element Violet is added, then at position 0 of the ArrayList, we add the item Red. At this point, the complete ArrayList looks like this, [Red, Violet].

Now, the element at index position 1 is replaced with the value Purple using the set method. After replacing the value, the ArrayList will look like this, [Red, Purple].

The remove Method

The ArrayList remove method is used for removing a value from the ArrayList. You can either pass the value or the index position of the value you want to remove. The syntax for the remove method is shown below:

arrayList.remove(Object value);

// or

arrayList.remove(int i);

Let’s take an example for a better understanding of the method. Assume that you have an ArrayList called rainbow with these values [Violet, Red, Green]. Now, if you want to remove Red from the ArrayList, you can write rainbow.remove("Red");. Calling this method on the rainbow ArrayList will remove the element Red from it.

// rainbow = [Violet, Red, Green]

rainbow.remove("Red");
System.out.println(rainbow);

Output:
[Violet, Green]

You can also pass the index position to remove the item at index position.

//rainbow = [Red, Green]

rainbow.remove(0); // Remove item at index position 0

System.out.println(rainbow);

Output:
[Green]

The clear Method

As the name suggests, the clear method removes all the elements from an ArrayList. The syntax is straightforward, and it doesn’t take any parameters.

arraylist.clear()

Let’s take a look at an example,

rainbow.clear(); 
System.out.println(rainbow); 

Output:
[]

The clear method doesn’t return any value. Instead, it clears the value of the given ArrayList.

The size Method

The size method returns the size of the given ArrayList. This method also doesn’t take any parameters. The syntax is shown below.

arrayList.size();

The arrayList is the name of the ArrayList here. Let’s understand the size method with the help of an example.

ArrayList rainbow = new ArrayList();
rainbow.add("Violet");
rainbow.add("Red");
rainbow.add("Green");

System.out.println(rainbow.size()); 


Output:
3

This method returns the value of the ArrayList size. In the above example, the ArrayList rainbow consists of three values, so the size method returns 3.

Conclusion

This article discussed what an ArrayList is and how it differs from an Array. We also saw how an ArrayList could be declared and used using various methods available for the ArrayList class.

If you want to dive deeper into learning Java, check out these online Java courses.