Description |
The TrimToSize method removes unused capacity from the current ArrayList. The new Capacity is therefore set equal to the Count of elements.
However, if the list has a Zero count. then the capacity is set to the default size of 16.
|
|
Microsoft MSDN Links |
System.Collections
System.Collections.ArrayList
|
|
|
Illustrating the effects of TrimToSize and Clear |
program Project1;
{$APPTYPE CONSOLE}
uses
System.Collections;
var
List : System.Collections.ArrayList;
i : Integer;
begin
// Create our array list object with a capacity if 10 elements
List := ArrayList.Create(10);
// Fill it
List.Add('0.');
List.Add('1.');
List.Add('2.');
List.Add('3.');
Console.WriteLine('List Count = {0}', List.Count.ToString);
Console.WriteLine('List Capacity = {0}', List.Capacity.ToString);
Console.WriteLine;
// Display List contents : note the 0 indexing
for i := 0 to List.Count-1 do
Console.WriteLine('List[{0}] = {1}', i.ToString, List[i]);
// Trim the array to remove unused elements
List.TrimToSize;
Console.WriteLine;
Console.WriteLine('After 1st TrimToSize :');
Console.WriteLine;
Console.WriteLine('List Count = {0}', List.Count.ToString);
Console.WriteLine('List Capacity = {0}', List.Capacity.ToString);
Console.WriteLine;
// Clear the array
List.Clear;
Console.WriteLine;
Console.WriteLine('After Clear :');
Console.WriteLine;
Console.WriteLine('List Count = {0}', List.Count.ToString);
Console.WriteLine('List Capacity = {0}', List.Capacity.ToString);
// Trim the array again
List.TrimToSize;
Console.WriteLine;
Console.WriteLine('After 2nd TrimToSize :');
Console.WriteLine;
Console.WriteLine('List Count = {0}', List.Count.ToString);
Console.WriteLine('List Capacity = {0}', List.Capacity.ToString);
Console.WriteLine;
Console.Readline;
end.
| Show full unit code | List Count = 4
List Capacity = 10
List[0] = 0.
List[1] = 1.
List[2] = 2.
List[3] = 3.
After 1st TrimToSize :
List Count = 4
List Capacity = 4
After Clear :
List Count = 0
List Capacity = 4
After 2nd TrimToSize :
List Count = 0
List Capacity = 16
|
|
|
|