Limiter la taille d'une ArrayList

Draco63 -  
 Draco63 -
Bonjour ou bonsoir,

je voudrais savoir si il y a un moyen d'affecter une taille limite a une ArrayList. Pour l'infos, mon ArrayList est une int.

Merci de votre aide.

2 réponses

  1. KX Messages postés 19031 Statut Modérateur 3 020
     
    Bonjour,

    La classe ArrayList ne gère pas de taille maximum, mais tu peux créer ta propre classe qui ferait la même chose. Par exemple :

    import java.util.*;
    
    public class ArrayListWithLimit<E> {
        private final ArrayList<E> innerList;
        private int maxSize;
    
        public ArrayListWithLimit(int maxSize) {
            innerList = new ArrayList<>();
            this.maxSize = maxSize;
        }
    
        public int size() {
            return innerList.size();
        }
    
        public int getMaxSize() {
            return maxSize;
        }
    
        public void setMaxSize(int maxSize) {
            if (size() > maxSize)
                throw new IllegalStateException("Can't set maxSize smaller than current size: " + size());
            this.maxSize = maxSize;
        }
    
        public boolean add(E element) {
            if (size() == getMaxSize())
                throw new IllegalStateException("Can't add an element because maxSize is reached: " + getMaxSize());
            return innerList.add(element);
        }
    
        public boolean addAll(Collection<? extends E> elements) {
            if (size() + elements.size() > getMaxSize())
                throw new IllegalStateException("Can't add all elements because maxSize would be exceeded: " + getMaxSize());
            return innerList.addAll(elements);
        }
    
        public E remove(int index) {
            return innerList.remove(index);
        }
    
        public E get(int index) {
            return innerList.get(index);
        }
    
        public E set(int index, E element) {
            return innerList.set(index, element);
        }
    
        @Override
        public String toString() {
            return innerList.toString();
        }
    
        @Override
        public int hashCode() {
            return innerList.hashCode();
        }
    
        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            return innerList.equals(((LimitedList<?>) obj).innerList);
        }
    }
    0