Collections in Java: ArrayList and LinkedList

Lesson 14 of 16 · Java

An array has a fixed length that is set when it is created. When the number of elements is not known in advance, you use a list from the java.util package: elements are added and removed, and the list grows by itself. This lesson covers ArrayList, LinkedList, going through a list, sorting and comparing objects.

Before you start: what you need to know first – arrays, classes and objects.
How to learn: type in and run each example, and try to solve the tasks at the end on your own first; open the hint and the solution only after that. All the programs are in Java (Java 17 or newer); each one has been compiled and run and gives the output shown.

ArrayList: basic operations

The type of the elements is given in angle brackets (a generic type). For primitive types the wrapper classes are used: Integer instead of int, Double instead of double, Character instead of char.

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Ana");                    // adds to the end
        names.add("Mark");
        names.add("Iva");
        names.add(1, "Luke");                // inserts at position 1
        System.out.println(names + " size " + names.size());

        System.out.println("At position 2: " + names.get(2));
        names.set(0, "Ana Maria");           // changes an element
        names.remove("Iva");                 // removes by value
        names.remove(0);                     // removes by position
        System.out.println(names);
        System.out.println("Contains Mark? " + names.contains("Mark") + ", position " + names.indexOf("Mark"));
    }
}

Output:

[Ana, Luke, Mark, Iva] size 4
At position 2: Mark
[Luke, Mark]
Contains Mark? true, position 1
ArrayArrayList
int[] a = new int[10];List<Integer> a = new ArrayList<>();
a.lengtha.size()
a[i]a.get(i)
a[i] = x;a.set(i, x);
the length is fixeda.add(x), a.remove(i)

Going through a list

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        ArrayList<Integer> numbers = new ArrayList<>();
        // read until 0 arrives – the number of elements is not known in advance
        int x;
        while ((x = sc.nextInt()) != 0)
            numbers.add(x);

        int sum = 0;
        for (int b : numbers)                 // for-each
            sum += b;
        System.out.println("Read " + numbers.size() + ", sum " + sum);

        // a classic loop when you need the index
        for (int i = 0; i < numbers.size(); i++)
            if (numbers.get(i) > sum / numbers.size())
                System.out.println("above average: " + numbers.get(i) + " (position " + i + ")");

        // removing while going through: removeIf (not remove in a for-each loop!)
        numbers.removeIf(b -> b % 2 == 0);
        System.out.println("Odd: " + numbers);
    }
}

Input: 5 8 2 9 0

Output:

Read 4, sum 24
above average: 8 (position 1)
above average: 9 (position 3)
Odd: [5, 9]

Removing elements in a for-each loop throws ConcurrentModificationException. Use removeIf with a condition (the lambda expression b -> b % 2 == 0 reads "an element b such that it is even") or a loop backwards by index.

Sorting: Collections.sort and Comparator

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> a = new ArrayList<>(List.of(5, 2, 9, 1, 7));
        Collections.sort(a);                              // ascending
        System.out.println(a);
        a.sort(Comparator.reverseOrder());                // descending
        System.out.println(a);
        System.out.println("max=" + Collections.max(a) + " min=" + Collections.min(a));

        List<String> words = new ArrayList<>(List.of("plum", "kiwi", "apple", "quince"));
        Collections.sort(words);                          // alphabetically
        System.out.println(words);
        words.sort(Comparator.comparing(String::length)); // by length (stable)
        System.out.println(words);
    }
}

Output:

[1, 2, 5, 7, 9]
[9, 7, 5, 2, 1]
max=9 min=1
[apple, kiwi, plum, quince]
[kiwi, plum, apple, quince]

List.of(...) creates a list that cannot be changed; that is why its elements are copied into new ArrayList<>(...).

A list of objects and sorting by several criteria

For your own classes the order is given by a Comparator. The comparing and thenComparing methods build a comparison by several fields:

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

public class Main {
    // record: a short way to write a class with fields, a constructor, getters and toString (Java 16+)
    record Student(String name, int grade, double average) { }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        List<Student> list = new ArrayList<>();
        for (int i = 0; i < n; i++)
            list.add(new Student(sc.next(), sc.nextInt(), Double.parseDouble(sc.next())));

        // by grade ascending, then by average descending, then by name
        list.sort(Comparator.comparingInt(Student::grade)
                .thenComparing(Student::average, Comparator.reverseOrder())
                .thenComparing(Student::name));

        for (Student s : list)
            System.out.println(s.grade() + ". " + s.name() + " " + s.average());
    }
}

Input: 4 Mark 8 4.20 Ana 7 4.85 Iva 8 4.75 Luke 7 4.85

Output:

7. Ana 4.85
7. Luke 4.85
8. Iva 4.75
8. Mark 4.2

Student::grade is a method reference – a shorter way to write s -> s.grade(). More about this in the lesson Lambda expressions and the Stream API.

LinkedList, queue and stack

LinkedList is a linked list: adding and removing at the start and the end is fast, but get(i) is slow (it goes from the start). For a queue and a stack, Java recommends ArrayDeque:

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;

public class Main {
    public static void main(String[] args) {
        // queue: first in – first out (FIFO)
        Queue<String> queue = new LinkedList<>();
        queue.offer("Ana");
        queue.offer("Mark");
        queue.offer("Iva");
        System.out.println("Next in line: " + queue.poll() + ", the others: " + queue);

        // stack: last in – first out (LIFO)
        Deque<Character> stack = new ArrayDeque<>();
        String expression = "(a+[b*c])";
        boolean correct = true;
        for (char c : expression.toCharArray()) {
            if (c == '(' || c == '[')
                stack.push(c);
            else if (c == ')' || c == ']') {
                char open = c == ')' ? '(' : '[';
                if (stack.isEmpty() || stack.pop() != open)
                    correct = false;
            }
        }
        System.out.println(expression + (correct && stack.isEmpty() ? " correct brackets" : " incorrect brackets"));
    }
}

Output:

Next in line: Ana, the others: [Mark, Iva]
(a+[b*c]) correct brackets
OperationArrayListLinkedList
get(i)fastslow (n steps)
adding to the endfastfast
adding/removing at the startslow (all elements move)fast

In practice ArrayList is used most often.

Practice tasks

Each task has an example, a hint and a solution. The solutions have been checked on the examples in the text.

TASK 01Difficulty: easy

No duplicates

Read n, then n whole numbers. Print the numbers without repetition, in the order in which they first appeared.

Example

Input

8
3 1 3 7 1 1 9 7

Output

3 1 7 9
TASK 02Difficulty: medium

A ranking list

Read n, then the name and the number of points of each competitor. Print the ranking list: more points is better, and with the same number of points the order is alphabetical. Competitors with the same number of points share the same place (after two second places comes fourth).

Example

Input

5
Mark 80
Ana 95
Iva 80
Luke 60
Sara 80

Output

1. Ana 95
2. Iva 80
2. Mark 80
2. Sara 80
5. Luke 60
Common mistakes and tips
  • A primitive type cannot go in angle brackets: List<int> is an error, you write List<Integer>.
  • With List<Integer> the call remove(3) removes the element at position 3; the value 3 is removed with remove(Integer.valueOf(3)).
  • Do not remove elements in a for-each loop – use removeIf.
  • Compare two Integer objects with equals (or convert them to int), not with ==.

Check your knowledge

Open the quiz

Lists in Java

1. How do you get the number of elements of the ArrayList a?




2. Which declaration is correct?




3. What is a stack?




4. Which method sorts the list list?