Labs ICT
โญ Pro Login

ArrayList

Regular arrays in Java have a fixed size. Once you create an array of size 5, you cannot add a sixth element. That is annoying when you do not know how many items you will need ahead of time.

ArrayList is like a resizable array. It grows and shrinks automatically as you add or remove items. It is part of the java.util package.

Creating an ArrayList

You have to specify the type of elements the list will hold inside angle brackets.

import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList names = new ArrayList<>();
  }
}

The tells Java this list will only hold String objects. The <> on the right is the diamond operator โ€” Java figures out the type from the left side.

Adding and Getting Elements

Use add() to put items in and get() to pull them out by index.

import java.util.ArrayList;

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

    names.add("Amina");
    names.add("Musa");
    names.add("Fatima");

    System.out.println(names.get(0));
    System.out.println(names.get(1));
    System.out.println(names.get(2));
  }
}

Indexes work the same as arrays โ€” starting from 0. get(0) gives you the first element, get(1) gives you the second, and so on.

Removing Elements and Checking Size

remove() deletes an element by index or by value. size() tells you how many elements are in the list.

import java.util.ArrayList;

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

    names.add("Amina");
    names.add("Musa");
    names.add("Fatima");

    names.remove(1);

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

    for (int i = 0; i < names.size(); i++) {
      System.out.println(names.get(i));
    }
  }
}

After remove(1), "Musa" is gone and the list shrinks. size() now returns 2. The loop goes through each element using the index.

Iterating Over an ArrayList

You can also use the enhanced for-each loop, which is cleaner when you do not need the index.

import java.util.ArrayList;

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

    names.add("Amina");
    names.add("Musa");
    names.add("Fatima");

    for (String name : names) {
      System.out.println(name);
    }
  }
}

The for-each loop goes through each element one by one. You do not have to worry about indexes, sizes, or off-by-one errors. It is the most common way to loop through an ArrayList.

๐Ÿงช Quick Quiz

What is the main difference between ArrayList and HashSet?