Analyse complète du code source d'ArrayList

Points clés : accès rapide, insertion/suppression lente, non thread-safe.

Diagramme d'héritage :

Diagramme d'héritage ArrayList

ArrayList implémente les interfaces suivantes :

  • List : fournit les opérations de base (ajout, suppression, parcours).
  • RandomAccess : permet un accès aléatoire efficace.
  • Cloneable : autorise le clonage.
  • Serializable : permet la sérialisation.
  1. Analyse du code source

2.1 Attributs

// Identifiant de sérialisation
private static final long serialVersionUID = 8683452581122892189L;

// Capacité par défaut du constructeur sans paramètre
private static final int DEFAULT_CAPACITY = 10;

// Tableau vide utilisé lorsque la capacité initiale est 0
private static final Object[] EMPTY_ELEMENTDATA = {};

// Tableau vide utilisé par le constructeur par défaut
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

// Tableau interne pour stocker les éléments (transient = non sérialisé)
transient Object[] elementData; 

// Nombre réel d'éléments
private int size;

// Taille maximale du tableau (dépasse → OutOfMemoryError)
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

2.2 Constructeurs

Trois constructeurs sont disponibles :

// Constructeur avec capacité initiale
public ArrayList(int initialCapacity) {
    if (initialCapacity > 0) {
        this.elementData = new Object[initialCapacity];
    } else if (initialCapacity == 0) {
        // Sera redimensionné lors du premier ajout
        this.elementData = EMPTY_ELEMENTDATA;
    } else {
        throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
    }
}

// Constructeur sans paramètre
public ArrayList() {
    // Lors du premier ajout, la capacité sera étendue à 10
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

// Constructeur à partir d'une collection
public ArrayList(Collection<? extends E> c) {
    elementData = c.toArray();
    if ((size = elementData.length) != 0) {
        // Vérifie que le tableau est de type Object[], sinon le recopie
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    } else {
        // Collection vide → tableau vide
        this.elementData = EMPTY_ELEMENTDATA;
    }
}

2.3 Méthodes simples

public int size() { return size; }

public boolean isEmpty() { return size == 0; }

public boolean contains(Object o) { return indexOf(o) >= 0; }

public Object[] toArray() { return Arrays.copyOf(elementData, size); }

2.4 Méthodes essentielles

add(E e)

Ajoute un élément à la fin de la liste.

public boolean add(E e) {
    ensureCapacityInternal(size + 1);
    elementData[size++] = e;
    return true;
}

private void ensureCapacityInternal(int minCapacity) {
    ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}

private static int calculateCapacity(Object[] elementData, int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        return Math.max(DEFAULT_CAPACITY, minCapacity);
    }
    return minCapacity;
}

private void ensureExplicitCapacity(int minCapacity) {
    modCount++;
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}

private void grow(int minCapacity) {
    int oldCapacity = elementData.length;
    // Nouvelle capacité = 1,5 fois l'ancienne
    int newCapacity = oldCapacity + (oldCapacity >> 1);
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);
    elementData = Arrays.copyOf(elementData, newCapacity);
}

add(int index, E element)

Insère un élément à une position donnée (complexité O(n)).

public void add(int index, E element) {
    rangeCheckForAdd(index);
    ensureCapacityInternal(size + 1);
    System.arraycopy(elementData, index, elementData, index + 1, size - index);
    elementData[index] = element;
    size++;
}

addAll(Collection c)

Ajoute tous les éléments d'une collection (union).

public boolean addAll(Collection<? extends E> c) {
    Object[] a = c.toArray();
    int numNew = a.length;
    ensureCapacityInternal(size + numNew);
    System.arraycopy(a, 0, elementData, size, numNew);
    size += numNew;
    return numNew != 0;
}

addAll(int index, Collection c)

Insère une collection à partir d'un index donné.

public boolean addAll(int index, Collection<? extends E> c) {
    rangeCheckForAdd(index);
    Object[] a = c.toArray();
    int numNew = a.length;
    ensureCapacityInternal(size + numNew);
    int numMoved = size - index;
    if (numMoved > 0)
        System.arraycopy(elementData, index, elementData, index + numNew, numMoved);
    System.arraycopy(a, 0, elementData, index, numNew);
    size += numNew;
    return numNew != 0;
}

get(int index)

Accès direct par index (O(1)).

public E get(int index) {
    rangeCheck(index);
    return elementData(index);
}

private void rangeCheck(int index) {
    if (index >= size)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

E elementData(int index) { return (E) elementData[index]; }

remove(int index)

Supprime l'élément à l'index donné.

public E remove(int index) {
    rangeCheck(index);
    modCount++;
    E oldValue = elementData(index);
    int numMoved = size - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index + 1, elementData, index, numMoved);
    elementData[--size] = null; // Aide au GC
    return oldValue;
}

remove(Object o)

Supprime la première occurrence de l'objet (O(n)).

public boolean remove(Object o) {
    if (o == null) {
        for (int index = 0; index < size; index++)
            if (elementData[index] == null) {
                fastRemove(index);
                return true;
            }
    } else {
        for (int index = 0; index < size; index++)
            if (o.equals(elementData[index])) {
                fastRemove(index);
                return true;
            }
    }
    return false;
}

private void fastRemove(int index) {
    modCount++;
    int numMoved = size - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index + 1, elementData, index, numMoved);
    elementData[--size] = null;
}

removeAll(Collection c)

Supprime tous les éléments présents dans la collection (différence).

public boolean removeAll(Collection<?> c) {
    Objects.requireNonNull(c);
    return batchRemove(c, false);
}

private boolean batchRemove(Collection<?> c, boolean complement) {
    final Object[] elementData = this.elementData;
    int r = 0, w = 0;
    boolean modified = false;
    try {
        for (; r < size; r++)
            if (c.contains(elementData[r]) == complement)
                elementData[w++] = elementData[r];
    } finally {
        if (r != size) {
            System.arraycopy(elementData, r, elementData, w, size - r);
            w += size - r;
        }
        if (w != size) {
            for (int i = w; i < size; i++)
                elementData[i] = null;
            modCount += size - w;
            size = w;
            modified = true;
        }
    }
    return modified;
}

retainAll(Collection c)

Garde uniquement les éléments communs (intersection).

public boolean retainAll(Collection<?> c) {
    Objects.requireNonNull(c);
    return batchRemove(c, true);
}

set(int index, E element)

Repmlace un élément (O(1)).

public E set(int index, E element) {
    rangeCheck(index);
    E oldValue = elementData(index);
    elementData[index] = element;
    return oldValue;
}

Itérateurs

Deux types d'itérateurs sont disponibles :

public Iterator<E> iterator() { return new Itr(); }

public ListIterator<E> listIterator() { return new ListItr(0); }

public ListIterator<E> listIterator(int index) {
    if (index < 0 || index > size)
        throw new IndexOutOfBoundsException("Index: " + index);
    return new ListItr(index);
}

// Itérateur simple (parcours avant)
private class Itr implements Iterator<E> {}

// ListIterator (parcours avant et arrière)
private class ListItr extends Itr implements ListIterator<E> {}

3. Résumé

  • ArrayList stocke ses éléments dans un tableau interne. En cas de dépassement de capacité, le tableau est agrandi de 50 % (1,5 fois). Il n'y a pas de mécanisme de réduction.
  • L'accès aléatoire est très rapide (O(1)).
  • Union : addAll(Collection c).
  • Intersection : retainAll(Collection c).
  • Différence : removeAll(Collection c).
  • Deux itérateurs permettent le parcours avant (Itr) ou bidirectionnel (ListItr).
  • Comme il repose sur un tableau, on peut aussi utiliser une boucle classique pour parcourir les éléments.
  • Avantages : rapidité de lecture. Inconvénients : lenteur lors des insertions/suppressions (surtout au milieu). Non thread-safe.

Étiquettes: ArrayList Java collection Tableau dynamique Code Source

Publié le 22 juillet à 10h11