English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
La méthode sureCapacity() de ArrayList Java ajuste la taille de ArrayList avec une capacité spécifiée.
La syntaxe de la méthode ensureCapacity() est :
arraylist.ensureCapacity(int minCapacity)
minCapacity - Capacité minimale spécifiée de ArrayList
La méthode sureCapacity() ne renvoie aucune valeur.
import java.util.ArrayList; class Main { public static void main(String[] args) { ArrayList<String> languages= new ArrayList<>(); //définir la capacité de l'ArrayList languages.ensureCapacity(3); //ajouter un élément dans ArrayList languages.add("Java"); languages.add("Python"); languages.add("C"); System.out.println("ArrayList: ", + languages); } }
Output result
ArrayList: [Java, Python, C]
Dans l'exemple précédent, nous avons créé une ArrayList nommée languages. Notez cette ligne,
languages.ensureCapacity(3);
ici, la méthode ensureCapacity() ajuste la taille de l'ArrayList pour stocker3éléments.
Cependant, ArrayList en Java peut ajuster sa taille dynamiquement. Autrement dit, si nous ajoutons3d'éléments ou plus, il ajuste automatiquement sa taille. Par exemple
import java.util.ArrayList; class Main { public static void main(String[] args) { ArrayList<String> languages= new ArrayList<>(); //définir la capacité de l'ArrayList languages.ensureCapacity(3); //ajouter un élément dans ArrayList languages.add("Java"); languages.add("Python"); languages.add("C"); //add the4elements languages.add("Swift"); System.out.println("ArrayList: ", + languages); } }
Output result
ArrayList: [Java, Python, C, Swift]
In the above example, we use ensureCapacity() method to adjust the size of arraylist to store3elements. But when we add the4an element, arraylist will automatically adjust its size.
then,If arraylist can automatically adjust its size,Why use guaranteeCapacity() method to adjust the size of arraylist?
This is because if we use ensureCapacity() to adjust the size of ArrayList, then the size will be adjusted immediately to the specified capacity.Otherwise, the size of arraylist will be adjusted each time an element is added.