๐ŸŽ“ A1Learner
๐Ÿ”

Java ArrayList

An ArrayList is a list that holds values in order and can change size. Values can be added, replaced, and removed after the list is created.

Add values and print the list

Three add calls fill the list. The size line counts the stored values.

import java.util.ArrayList;
public class Main {
  public static void main(String[] args) {
    ArrayList<String> fruits = new ArrayList<String>();
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Cherry");
    System.out.println(fruits);
    System.out.println(fruits.size());
  }
}

Read, replace, and remove values

The get call reads the first value. The set call replaces the second value, and the remove call deletes the first value.

import java.util.ArrayList;
public class Main {
  public static void main(String[] args) {
    ArrayList<String> fruits = new ArrayList<String>();
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Cherry");
    System.out.println(fruits.get(0));
    fruits.set(1, "Mango");
    System.out.println(fruits);
    fruits.remove(0);
    System.out.println(fruits);
  }
}

Sort the list

The values are added out of order. The sort call puts the list in order.

import java.util.ArrayList;
import java.util.Collections;
public class Main {
  public static void main(String[] args) {
    ArrayList<String> fruits = new ArrayList<String>();
    fruits.add("Cherry");
    fruits.add("Apple");
    fruits.add("Banana");
    Collections.sort(fruits);
    System.out.println(fruits);
  }
}

Example

import java.util.ArrayList;
import java.util.Collections;
public class Main {
  public static void main(String[] args) {
    ArrayList<String> cities = new ArrayList<String>();
    cities.add("Quito");
    cities.add("Oslo");
    cities.add("Perth");
    Collections.sort(cities);
    for (String city : cities) {
      System.out.println(city);
    }
    System.out.println(cities.size());
  }
}

Key points

  • An ArrayList is created with new, and the held type is named in angle brackets.
  • The add method appends a value at the end of the list.
  • The get method reads the value at an index.
  • The set method replaces the value at an index.
  • The remove method deletes the value at an index.
  • The size method returns the number of values in the list.
  • The sort method of the Collections class puts a list in order.

In this example, three city names are added out of order. The sort call puts the names in order. The loop then prints one name per line. The last line prints the count of names in the list.

Note

Printing an ArrayList shows its values in square brackets.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Java Compiler

Exercise

Which method adds a value at the end of an ArrayList?