Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

ArrayList — a list and its collection-copy constructor

ArrayList is a mutable list backed by a resizable array. The ArrayList(Collection) constructor creates a separate list from a collection's elements.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

ArrayList<E> list = new ArrayList<>(collection);
// Constructor: public ArrayList(Collection<? extends E> c)

java.util.ArrayList<E> implements List<E> using a resizable array. It permits duplicates and null. size() is the element count, not the array capacity.

ArrayList(Collection), precisely public ArrayList(Collection<? extends E> c), creates a list in c's iterator order. It accepts elements of type E or its subtypes. Passing null instead of a collection throws NullPointerException.

This is a shallow copy: the lists have independent structure but share element references. Changing a shared mutable object can be visible through both lists.

get and set cost O(1); appending costs amortized O(1). The list is not synchronized; concurrent access involving structural changes requires external synchronization.

Examples

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> source = new ArrayList<>();
        source.add("A");
        source.add("B");

        ArrayList<String> copy = new ArrayList<>(source);
        copy.set(0, "X");
        copy.add("C");

        System.out.println(source);
        System.out.println(copy);
    }
}

Result

[A, B]
[X, B, C]

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources