Description |
Repeat is an awkwardly named method. It creates a new ArrayList object with Count elements, all set to the same Value.
Repeat performs a shallow build. When Value is a reference (non primitive) data type, the built array element values all refer to the same object. This is what is referred to as a shallow build. A deep build would create new objects for each array element.
|
|
Microsoft MSDN Links |
System.Collections
System.Collections.ArrayList
|
|
|
A simple example |
program Project1;
{$APPTYPE CONSOLE}
uses
System.Collections;
var
MyList : System.Collections.ArrayList;
i : Integer;
begin
// Create an array of 3 strings all with the same value
MyList := System.Collections.ArrayList.Repeat('Same', 3);
// Display the array
for i := 0 to MyList.Count-1 do
Console.WriteLine(MyList.Item[i]);
Console.ReadLine;
end.
| Show full unit code | Same
Same
Same
| | Illustrating the shallowness of the Repeat method | program Project1;
{$APPTYPE CONSOLE}
uses
System.Collections;
type
MyClass = Class
private
mcName : String;
published
Property Name : String
read mcName
write mcName;
Constructor Create(Name : String); overload;
Function ToString : String; overload;
end;
// MyClass methods
constructor MyClass.Create(Name : String);
begin
inherited Create;
mcName := Name;
end;
function MyClass.ToString : String;
begin
Result := Name;
end;
// Main code
var
MyList : System.Collections.ArrayList;
MyObject : MyClass;
i : Integer;
begin
// Create an array of 3 strings all with the same value
MyList := System.Collections.ArrayList.Repeat(MyClass.Create('Same'), 3);
// Display the array
for i := 0 to MyList.Count-1 do
begin
MyObject := MyClass(MyList.Item[i]);
Console.WriteLine(MyObject.ToString);
end;
Console.WriteLine;
Console.WriteLine('After updating just the middle element :');
Console.WriteLine;
// Updating the middle element only
MyObject := MyClass(MyList.Item[1]);
MyObject.Name := 'Different';
// Display the array
for i := 0 to MyList.Count-1 do
begin
MyObject := MyClass(MyList.Item[i]);
Console.WriteLine(MyObject.ToString);
end;
Console.ReadLine;
end.
| Show full unit code | Same
Same
Same
After updating just the middle element :
Different
Different
Different
|
|
|
|