TList

From Free Pascal wiki
Revision as of 10:44, 24 March 2021 by Dbannon (talk | contribs) (First cut at a page about tList and TFPList)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

TList and TFPList are classes that can be used to manage collections of pointers. These pointers may conveniently point to, for example, records as in the following example -

type
  	PNote=^TNote;
  	TNote = record
		Name : ANSIString;
        IsSilly : boolean;
        NumbHeads : integer;
	end;

type
    // Note we can use TFPList (faster) or TList (and get event notification)
   TNoteList = class(TList)
   private
    	function Get(Index: integer): PNote;
    public
        destructor Destroy; override;
        function Add(ANote : PNote) : integer;
        function FindName(const Name : ANSIString) : PNote;
        property Items[Index: integer]: PNote read Get; default;
    end;


implementation

function TNoteList.Get(Index: integer): PNote;
begin
    Result := PNote(inherited get(Index));
end;

function TNoteList.Add(ANote: PNote): integer;
begin
    result := inherited Add(ANote);
end;

function TNoteList.FindName(const Name: ANSIString): PNote;
var
    P : PNote;
begin
    Result := Nil;
    for P in self do
        if P^.Name = Name then exit(P);
end;

destructor TNoteList.Destroy;
var
  I : integer;
begin
	for I := 0 to Count-1 do begin
    	dispose(Items[I]);
	end;
	inherited Destroy;
end;                                         
....

In this example, that can use either TList or TFPList, we make a record that will hold one "item of data", and, to make things easy, we also declare a type pointer to that sort of record. Its sensible to put code like this in its own unit and a practical use will almost certainly require a few extra methods to manage the data it self.

To use this example, we need to declare a variable of type TNoteList and then create and destroy it. So, perhaps in a FormCreate we would have -

NoteList := TNoteList.Create;

and in FormDestroy we might have -

NoteList.free;

To load some data we would perhaps use -

procedure TForm1.LoadData();
var
    P : PNote;     // P is a pointer to a note record, somewhere !
begin
    AddNote('Joe', False, 1);
    AddNote('Harry', True, 1);
    AddNote('David', True, 2);     // Tasmanian
    AddNote('Boris', False, 1);
end;

and to use that data we might have -

procedure TForm1.UseData();
var
    P : PNote;     // P is a pointer to a note record, somewhere !
begin
    P := NoteList.FindName('David');
    if P <> nil then
        writeln('David has ' + P^.NumbHeads.ToString + ' heads');
    for P in NoteList do
        if P^.IsSilly then
            writeln(P^.Name + ' is silly');
    if NoteList.FindName('George') = nil then
        writeln('George is not listed');
end;