← 講座に戻る: Java from scratch

ArrayList: lists that grow

動画は近日公開

The big limit of an array is its fixed size. In real life lists change: tasks are added, products are removed from the cart, new messages arrive. For that Java offers ArrayList, a list that grows and shrinks by itself. Inside it uses an array and replaces it with a bigger one when it fills up, but you do not have to worry about that. It is the collection you will use the most in your career, so it deserves to be mastered.

Creating and using a list

ArrayList lives in java.util and is generic: between the < > signs you state the type of the elements, for example ArrayList<String>. Generics do not accept primitive types, so for numbers you use wrapper classes: Integer instead of int, Double instead of double, Boolean, Character, Long. Java converts between both automatically (autoboxing). In real code you usually declare the variable with the List interface and create the object with ArrayList: List<String> names = new ArrayList<>(); the diamond operator <> avoids repeating the type.

java
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");
        names.add("Luis");
        names.add("Marta");
        names.add(1, "Pedro");                 // insert at index 1
        System.out.println(names);             // [Ana, Pedro, Luis, Marta]
        System.out.println(names.size());      // 4
        System.out.println(names.get(2));      // Luis

        names.set(0, "Anna");                  // replace
        names.remove("Luis");                  // remove by value
        names.remove(0);                       // remove by index
        System.out.println(names);             // [Pedro, Marta]

        System.out.println(names.contains("Marta"));   // true
        System.out.println(names.indexOf("Marta"));    // 1
        System.out.println(names.isEmpty());           // false

        for (String n : names) {
            System.out.println("Hello " + n);
        }

        // Wrapper types: List<int> does not compile, List<Integer> does
        List<Integer> numbers = new ArrayList<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);
        int total = 0;
        for (int x : numbers) total += x;      // unboxing
        System.out.println(total);             // 60

        numbers.clear();
        System.out.println(numbers.size());    // 0
    }
}

A trap with remove

In a list of Integer, remove has two versions that get mixed up: remove(int index) deletes a position and remove(Object o) deletes a value. If you write numbers.remove(1), Java understands an index. To delete the value 1 you must write numbers.remove(Integer.valueOf(1)). Another classic mistake is modifying the list while walking through it with for-each: it throws ConcurrentModificationException. To delete elements that meet a condition use removeIf, which does it safely with a lambda expression (we will see them in depth in week 8).

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

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>(List.of(5, 1, 9, 1, 7));

        numbers.remove(1);                       // index 1: removes the first 1
        System.out.println(numbers);             // [5, 9, 1, 7]
        numbers.remove(Integer.valueOf(9));      // value 9
        System.out.println(numbers);             // [5, 1, 7]

        numbers.add(12);
        numbers.add(20);
        numbers.removeIf(n -> n % 2 == 0);       // remove all even numbers
        System.out.println(numbers);             // [5, 1, 7]

        Collections.sort(numbers);
        System.out.println(numbers);             // [1, 5, 7]
        System.out.println(Collections.max(numbers)); // 7

        List<String> fixed = List.of("a", "b");  // immutable list
        try {
            fixed.add("c");
        } catch (UnsupportedOperationException e) {
            System.out.println("List.of is read-only");
        }

        try {
            for (Integer n : numbers) {
                if (n == 1) numbers.remove(n);   // modifying while iterating
            }
        } catch (java.util.ConcurrentModificationException e) {
            System.out.println("Do not remove inside for-each");
        }
    }
}

Array or ArrayList: when to use each

  • Use an array when the size is fixed and known in advance, or when you work with primitives and performance matters (for example, processing millions of numbers).
  • Use ArrayList when the number of elements changes during the program: tasks, users, search results.
  • The array uses brackets and length; ArrayList uses methods: get, set, add, size.
  • ArrayList offers ready-made methods (contains, indexOf, remove, sort) that with an array you would have to program by hand.
  • Accessing a position by index is fast in both; inserting or deleting in the middle of an ArrayList shifts the following elements, so it is slower in huge lists.

One last detail about comparing elements: contains, indexOf and remove(Object) use the equals method of the elements. With String and Integer it works as you expect, because they compare content. When you store your own objects, you will have to define equals properly; we will see it in the object-oriented programming week.

理解度チェック

問題 1 / 1

How do you declare a list of integers?

✎ マイノート

このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字

← 前へ次へ →