We consider a scenario where we need to add a very large number of elements to an ArrayList of insufficient size, in such a case, the ArrayList has to be resized several times and this will lead to poor performance. This problem can be addressed by calling the ensureCapacity() which is very useful for ensuring or increasing the capacity of an ArrayList.
public void ensureCapacity(int minCapacity): This method resets the minimum capacity of ArrayList.
import java.util.ArrayList;Runtime:
public class ArrayList_ensureCapacity {
public static void main(String[] args) {
ArrayList< String> arraylist = new ArrayList< String> (4);
//Add Items to ArrayList
arraylist.add("Screen");
arraylist.add("TV");
arraylist.add("Laptop");
arraylist.add("Tablet");
arraylist.ensureCapacity(5);
arraylist.add("Smartphone");
System.out.println("ArrayList Elements: ");
for(String s:arraylist)
System.out.println(s);
}
}
ArrayList items:
Screen
TV
Laptop
Tablet
Smartphone
Commentaires (12)
Connectez-vous pour commenter
Rejoignez la discussion et partagez vos connaissances avec la communauté
Excellent tutoriel !
N'hésitez pas si vous avez des questions.