Title: List (array) of pointers
Question: TList can stores an array of pointers. Is generally used to maintain
lists of objects.
Answer:
//---------------------------------------------------------------------------
// Author : Digital Survivor [Esteban Rodrguez Nieto | Jos Plano]
// Email : plmad666@gmail.com | jose.plano@gmail.com
// Web site : www.ds-studios.com.ar
//---------------------------------------------------------------------------
TList can stores an array of pointers. Is generally used to maintain
lists of objects. TList have also properties and methods to:
* Add or delete the objects in the list.
* Rearrange the objects in the list.
* Locate and access objects in the list.
* Sort the objects in the list.
{ This piece of code create a TList class variable and fills it with pointers }
{ Declarations }
Uses
Windows, Classes;
Type
PItem = ^TItem; // Declares a pointer type
TItem = Record
Name : String [10];
Number : Word;
Var
Item : PItem;
ItemList : TList; // Declares the pointer list variable
{ To add items (pointers) to the list, you can do these }
Begin
ItemList := TList.Create; // Creates the pointer list variable
For Cont := 1 To 10 Do
Begin
Item := New (PItem); // Assign memory to the pointer
Item^.Name := IntToStr (Cont); // Fills the name
Item^.Number := Cont; // Fills the number
ItemList.Add (Item); // Adds the filled pointer to the list
End;
End;
{ ----- End of the filling procedure ----- }
{ To access the pointer list, you can do these }
Var
W : Word;
S : String;
Begin
Item := New (PItem);
Item := ItemList [0];
S := ItemList^.Name;
W := ItemList^.Number;
End;
{ ----- End of the accessing procedure ----- }
{ To delete an item from the list, you can do these }
Begin
ItemList.Delete [8]; // This delete the 9th element of the list. Remember that index of the fist item is 0
ItemList.Clear; // This line clears all the items in the list
End;
{ ----- End of the deleting procedure ----- }
{ To replace an existing item in the list, do these }
Begin
Item := New (PItem); // Assign memory to the pointer
Item^.Name := IntToStr ('New Text'); // Fills the name
Item^.Number := 666; // Fills the number
ItemList.Items [5] := Item; // Replaces the 6th item of the list with the new filled pointer
End;
{ ----- End of the replacing procedure ----- }
Note: To destroy the whole List object, siply call Free funtion.
For example:
ItemList.Free;