ArrayList size, trim to size and capacity
In this chapter you will learn:
- How to increases the capacity of an ArrayList
- How to get the size and trim to size for an ArrayList
- If ArrayList is empty
Increases the capacity of an ArrayList
You can increase the capacity of an ArrayList
object manually by
calling ensureCapacity( )
.
By increasing its capacity once, at the start, you can prevent several reallocations later.
void ensureCapacity(int minCapacity)
Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
import java.util.ArrayList;
//from j a v a 2 s . c o m
public class Main {
public static void main(String args[]) {
ArrayList<String> al = new ArrayList<String>();
al.add("C");
al.add("A");
al.add("E");
al.add("java2s.com");
al.add("D");
al.add("F");
al.add(1, "java2s.com");
System.out.println(al);
System.out.println(al.size());
al.ensureCapacity(100);
System.out.println(al.size());
}
}
The output:
Get the size and trim to size
To reduce the size of the array, call trimToSize()
int size()
Returns the number of elements in this list.void trimToSize()
Trims the capacity of this ArrayList instance to be the list's current size.
import java.util.ArrayList;
//from j a v a 2 s . c om
public class Main {
public static void main(String args[]) {
ArrayList<String> al = new ArrayList<String>();
al.add("C");
al.add("java2s.com");
al.add("D");
al.add("F");
al.add(1, "java2s.com");
al.trimToSize();
System.out.println(al.size());
}
}
The output:
If ArrayList is empty
boolean isEmpty()
returns true if this list contains no elements.
import java.util.ArrayList;
//from ja v a 2 s .com
public class Main {
public static void main(String args[]) {
ArrayList<String> al = new ArrayList<String>();
al.add("C");
al.add("java2s.com");
al.add("D");
al.add("F");
al.add(1, "java2s.com");
System.out.println(al.isEmpty());
al.clear();
System.out.println(al.isEmpty());
}
}
The output:
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » List