A voir également:
- Limiter la taille d'une ArrayList
- Réduire la taille d'un pdf - Guide
- Taille 32x32 correspondance ✓ - Forum Loisirs / Divertissements
- Comment reduire la taille d'une photo - Guide
- W32 l32 taille française homme ✓ - Forum Loisirs / Divertissements
- Curseur plus large que 32x32 - Forum Windows
2 réponses
KX
Messages postés
16668
Date d'inscription
samedi 31 mai 2008
Statut
Modérateur
Dernière intervention
17 mars 2023
3 005
9 juin 2020 à 08:42
9 juin 2020 à 08:42
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 :
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);
}
}