Logo

Programming-Idioms

  • Java
  • Pascal

Idiom #306 Ensure list capacity

Preallocate memory in the list x for a minimum total capacity of 200 elements.

This is not possible in all languages. It is only meant as a performance optimization, should not change the length of x, and should not have any effect on correctness.

Uses Classes;
x.capacity := 200;
SetLength(a, 200);

Using Dynamic Arrays.
Initializes a with 200 zeroes
import java.util.ArrayList;
import java.util.List;
List<T> x = new ArrayList<>(200);
import java.util.ArrayList;
ArrayList<?> x = new ArrayList<>();
x.ensureCapacity(200);

The default capacity is 10.
with Ada.Containers.Vectors;
declare
   X : Vector;
begin
   Reserve_Capacity (X, Capacity => 200);
end;

New implementation...
< >
programming-idioms.org