Algorithm Math Delphi

Title: How to realize a dynamic array
Question: How to manage a dynamic list easily with TList and no pointers.
Answer:
TList is very useful to manage a list of objects and handle it like
an array. The only thing is a typecast that is needed to access the
data (if you don't wont to subclass from TList).
You need an own class for holding the data - e.g. a string:
type
TMyDataPoint = class
public
Data1: string;
constructor Create(aData1: string);
end;
The constructer sets the string:
constructor TMyDataPoint.Create(aData1: string);
begin
Data1 := aData1;
end;
An object of the class TList must be created:
var
MyList : TList;
...
MyList := TList.Create;
One line of code is enough to add an element:
MyList.Add(TMyDataPoint.Create(Edit1.Text));
TList owns methode e.g. for find, delete or sort (quicksort) the
elements (objects). These methods are returning a pointer - so a
typecast must be performed to access the string:
This is the access for the first element:
Edit1.Text := TMyDataPoint(MyList.Items[1]).Data1;
This is how to fill a memo with all elements:
var
i: integer;
...
for i := 0 to MyList.Count-1 do
Memo1.Lines.Add(TMyDataPoint(MyList.Items[i]).Data1);
Before you delete the list-objects - all elements must be destroyed:
var
i: integer;
...
for i := 0 to MyList.Count-1 do
TMyDataPoint(MyList.Items[i]).Destroy;
MyList.Destroy;
A 'cleaner' version is to create a TMyList that handles the typecast and destroys all elements automatically.
Note: If you use Delphi 5 - check out TObjectList !