In this example, we have defined an ArrayList with capacity 30. After adding 10 elements, we called the method trimToSize() which reduces the size of the list from 30 items to 10.
import java.util.ArrayList;Runtime:
public class ArrayList_Trim {
public static void main(String[] args) {
ArrayList< Integer> al = new ArrayList< Integer> ();
//minimum capacity of 50 elements
al.ensureCapacity(50);
al.add(1);
al.add(2);
al.add(3);
al.add(4);
al.add(5);
al.add(6);
al.add(7);
al.add(8);
al.add(9);
al.add(10);
al.trimToSize();
System.out.println(al.size());
for(Integer n:al)
System.out.println(n);
}
}
10
1
2
3
4
5
6
7
8
9
10
Commentaires (0)
Laisser un commentaire
Connectez-vous pour commenter
Rejoignez la discussion et partagez vos connaissances avec la communauté
Chargement des commentaires...