[solved] Using TLists lazarus / 21-General ---------------------------------------------------------------------- andyH · 2021-02-01 15:46 I'm replacing an application where I use arrays of records with TLists and TObjects. I have looked at this http://www.atug.com/andypatterns/collections.htm, specifically: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i var  FBirds : TList;    function TBirds.GetBirds(Index: Integer): TBird;begin  result := TBird( FBirds[Index] );end;    //so rather than everyone doing  TBird( Birds[50] )    //they only have to do  Birds[50]    //in order to get a TBird object out of the FBirds list.which is exactly what I want to do, replace TBird(Birds[j]) with Birds[j]. I understand TBird and TList but where is Tbirds coming from? So I set up: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i type  TBird = class(TObject)    btype : string; //e.g. robin    population : integer; //e.g. 100,000    area : string; //e.g. southwest    constructor create;  end;   TBirdList = class(TList)    function getBirds(Index : integer) : TBird;  end; var  MyBirds : TBirdList;  Bird: TBird; with Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function TBirdList.GetBirds(Index: Integer): TBird;begin  result := TBird(MyBirds[Index]);end;I thought was a bad idea to reference a variable within a method, so replaced result := TBird(MyBirds[Index]) with result := TBird(self[Index]). Better, but didn't change the outcome. In the main program: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i writeln('btype =',TBird(MyBirds[0]).btype);  //okay but what I'm trying to changewriteln('btype =',MyBirds[0].btype);   //ERROR - illegal qualifier, but what I wantwriteln('btype =',MyBirds.getBirds(0).btype); //okay, but not want I'm trying to do I suspect the link is only telling part of the story or plain wrong. What do I have to do so that I can use MyBirds[j].btype instead of TBird(MyBirds[j]).btype to both assign and read values from it? If I can sort this, I have a couple of supplementaries: Would it be better to use TCollection and TCollectionItem instead of TList and TObject? As I understand it, TCollection.free will free all TCollectionItems while TList.free does not free the TObjects.I actually have a nested TList, i.e. a TList within TBird, e.g. subspecies with elements such as #, colour. How to reference as MyBirds[z].subspecies[y].colour:= blue. Currently I'm having to do with TBird(Mybirds[z]) do subspecies[y].colour:= blue, ungainly. ---------------------------------------------------------------------- lucamar · 2021-02-01 16:52 Truth be told, that page seems a little confussing since it talks just about general concepts and skips several details. In this particular case he's talking about encapsulating the list inside another "wrapping" class, which might be something like (very simplified: it'll need a constructor, destructor, etc.): Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i TBirds = classprivate  FBirds: TList;  function GetBird(Index: Integer): TBird;public  property Bird[Index: Integer]: TBird read GetBird; default;end; Only he seems to be using, for some queer reason, a global var FBirds instead of a class field. I don't quite understand why: a wrapping class serves precisely to hide those implementation details as much as possible. ETA: Talk about missing details ... Quote from: andyH on February 01, 2021, 04:46:37 pmWould it be better to use TCollection and TCollectionItem instead of TList and TObject? As I understand it, TCollection.free will free all TCollectionItems while TList.free does not free the TObjects. Depends, but note that you can (and should!) free both the list and its objects in TBirds's destructor. Unless your list is extremely large and/or you use lots of them there should be only a small performance hit, if any.  QuoteI actually have a nested TList, i.e. a TList within TBird, e.g. subspecies with elements such as #, colour. How to reference as MyBirds[z].subspecies[y].colour:= blue. Currently I'm having to do with TBird(Mybirds[z]) do subspecies[y].colour:= blue, ungainly. Should be evident now: MyBirds.Bird[x] returns a TBird instance so you can access any of TBird properties/methods normally.[/tt] returns a TBird instance so you can access any of TBird properties/methods normally. Note also that by marking Bird[] as Default you can use either: MyBirds.Bird[x].Whatever or MyBirds[x].Whatever with perfect impunity ---------------------------------------------------------------------- andyH · 2021-02-01 18:37 Thanks for that, something to play with. Might be a few days, spent so long on this that I've been directed onto other none PC tasks. I will use Tcollection and Tcollectionitem, the lists are not long. ---------------------------------------------------------------------- egsuh · 2021-02-02 07:10 I haven't used TCollection. But AFAIK you can collect only the same classes in TCollection, not descendants. ---------------------------------------------------------------------- PascalDragon · 2021-02-02 08:01 Quote from: andyH on February 01, 2021, 04:46:37 pmI suspect the link is only telling part of the story or plain wrong. What do I have to do so that I can use MyBirds[j].btype instead of TBird(MyBirds[j]).btype to both assign and read values from it? In your specific example you'd have to reimplement the Items property: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i type  TBirdList = class(TList)  private    function GetItems(aIndex: Integer): TBird;    procedure SetItems(aIndex: Integer; aBird: TBird);  public    property Items[Index: Integer]: TBird read GetItems write SetItems; default;  end; The default is necessary so that you can access it as mybirds[ i ] instead of mybirds.Items[ i ]. However if you're working with classes I'd suggest you to use TObjectList instead of TList, because the former will free the contained class instances upon freeing the list (or deleting an item) if the OwnsObjects property is set to True (or if it was created with the corresponding parameter set to True). Additionally you might want to take a look at generic lists like fgl.TFPGObjectList<> or Generics.Collections.TObjectList<> where you don't need to write additional code, but can simply do TBirdList = specialize TFPGObjectList or TBirdList = specialize TObjectList (if you use mode Delphi then the specialize needs to be dropped). Quote from: andyH on February 01, 2021, 04:46:37 pmIf I can sort this, I have a couple of supplementaries: Would it be better to use TCollection and TCollectionItem instead of TList and TObject? As I understand it, TCollection.free will free all TCollectionItems while TList.free does not free the TObjects. TCollection and TCollectionItem are rather heavy weight. They are mainly interesting if you're working with GUI components or if you want to take advantage of the streaming system provided by the Classes unit. For simply keeping a list of class instances I'd stay with the list classes (generic or not). Quote from: andyH on February 01, 2021, 04:46:37 pmI actually have a nested TList, i.e. a TList within TBird, e.g. subspecies with elements such as #, colour. How to reference as MyBirds[z].subspecies[y].colour:= blue. Currently I'm having to do with TBird(Mybirds[z]) do subspecies[y].colour:= blue, ungainly. You'd simply do TBird(MyBirds[ z ]).SubSpecies[ y ].colour if your SubSpecies provides a correct default property as well. Otherwise you'd have to cast here as well. Or with either the adjusted example above or by using one of the generic lists you can do MyBirds[z].SubSpezies[y].Colour. Essentially you need to treat each level separately and once you've done that you can combine them as you need it. ---------------------------------------------------------------------- andyH · 2021-02-02 10:09 Thanks, particularly the advice on TObjectList. I'm beginning to get my head around encapsulation. ---------------------------------------------------------------------- andyH · 2021-02-09 14:48 Stuck, and not for the want of googling  I followed PascalDragon's advice and defined TBirdList as : Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i TBirdList = class(TObjectList)  private    function GetItems(aIndex: Integer): TBird;     procedure SetItems(aIndex: Integer; aBird: TBird); //not implemented yet  public    property Items[Index: Integer]: TBird read GetItems write SetItems; //default;  end; I commented out default to remove just one potential source of error, not that it made any difference. with GetItems defined as: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function TBirdList.GetItems(aIndex: Integer): TBird;begin     result:= TBird(self[aIndex]); //results in a exception class 'External: SIGSEGV'.end; In the main body:  Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i //code to create MyBirds and add a couple of instances of Bird to it.writeln('number of birds=',MyBirds.count); //okay = 2writeln('bird 0 =',Tbird(Mybirds[0]).btype);//okay = robinTbird(Mybirds[0]).btype:= 'hawk'; writeln('bird 0 =',Tbird(Mybirds[0]).btype);//okay = hawk //but the following generates a SIGSEGV error at//result:= TBird(self[aIndex]); in TBirdList.GetItemswriteln('new bird 0 ',Mybirds.items[0].btype); googling a SIGSEGV error seems to suggest that the object doesn't exist but it does. To try and figure out what was going wrong, I recast GetItems to return a string result with Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i result:= TBird(self[aIndex]).btype;with other consequent changes. and it worked in the main body: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i writeln('new bird 0 ',Mybirds.items[0]); //okay = hawk   Which rather than aiding has just further confused me, what is wrong with result:= TBird(self[aIndex]). It doesn't seem to be returning an instance of TBird ? ---------------------------------------------------------------------- andyH · 2021-02-09 17:33 Sorted! The problem was with Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i property Items[Index: Integer]: TBird read GetItems; default; then Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i writeln('bird 0 =',Tbird(Mybirds[0]).btype);  would fail. Commenting default out, it was okay and Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i writeln('new new bird 0 ',Mybirds.items[0].btype); worked. I think I know what I'm doing now. ---------------------------------------------------------------------- andyH · 2021-02-09 18:32 One step forward, two back. Having got Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i writeln('new bird 0 ',Mybirds.items[0].btype); working with Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i property Items[Index: Integer]: TBird read GetItems;in the definition for TBirdList, I added default back in: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i property Items[Index: Integer]: TBird read GetItems; default;   with the expectation that this would work Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i writeln('new bird 0 ',Mybirds[0].btype); No, got a SIGSEGV error on result:= TBird(self[aIndex]) in TBirdList.GetItems. Now I am stuck, I think that self[aIndex] needs to access the original default function but no idea how to do it. ---------------------------------------------------------------------- bytebites · 2021-02-09 19:03 Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function TBirdList.GetItems(aIndex: Integer): TBird;begin  result:= TBird(get(aindex));end; procedure TBirdList.SetItems(aIndex: Integer; aBird: TBird);begin   put(aIndex,aBird);end; ---------------------------------------------------------------------- howardpc · 2021-02-09 21:25 Here's a basic compilable example: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program project1; {$mode objfpc}{$H+} uses  Classes, Contnrs, SysUtils; type   TBird = class(TObject)    area: String;    birdType: String;    population: Integer;    constructor Create(aType, anArea: String; aPopulation: Integer); reintroduce;  end;   TBirdList = class(TFPObjectList)  private    function GetBirds(anIndex: Integer): TBird;    procedure SetBirds(anIndex: Integer; aValue: TBird);    procedure ConsoleReportBird(anIndex: Integer);  public    procedure ReportFlock;    property Birds[anIndex: Integer]: TBird read GetBirds write SetBirds; default;  end; function SortByType(Item1, Item2: Pointer): Integer;var  bird1: TBird absolute Item1;  bird2: TBird absolute Item2;begin  Result := AnsiCompareText(bird1.birdType, bird2.birdType);end; procedure TBirdList.ConsoleReportBird(anIndex: Integer);begin  with Birds[anIndex] do // or // with GetBirds(anIndex) do    WriteLn(birdType, ' found in ',area,'; population: ',population);end; function TBirdList.GetBirds(anIndex: Integer): TBird;begin  case ((anIndex > -1) and (anIndex < Count)) of    True:  Exit(TBird(GetItem(anIndex)));    False: Exit(Nil);  end;end; procedure TBirdList.ReportFlock;var  i: Integer;begin  for i := 0 to Count-1 do    ConsoleReportBird(i);end; procedure TBirdList.SetBirds(anIndex: Integer; aValue: TBird);begin  SetItem(anIndex, aValue);end; constructor TBird.Create(aType, anArea: String; aPopulation: Integer);begin  inherited Create; // not actually necessary here  area := anArea;  birdType := aType;  population := aPopulation;end; var  MyBirds : TBirdList; begin  MyBirds := TBirdList.Create(True);  try    with MyBirds do      begin        Add(TBird.Create('starling', 'urban', 10000));        Add(TBird.Create('hawk', 'southwest', 300));        Add(TBird.Create('owl', 'lowlands', 2000));        Add(TBird.Create('avocet', 'saltmarsh', 30));        ReportFlock;      WriteLn;        Sort(@SortByType);        ReportFlock;      end;  finally    MyBirds.Free;  end;  Write(#10'Press Enter to finish');  ReadLn;end. ---------------------------------------------------------------------- andyH · 2021-02-09 23:16 Thanks to both of you, too late here to try, so tomorrow... bytebites - I'd figured why it was wrong, but couldn't sort out the syntax to fix which you have now given me. howardpc - and thanks for going above and beyond with a 'complete' solution', particularly the sort function which is further down my to- do list. I'll have a play. ---------------------------------------------------------------------- PascalDragon · 2021-02-10 08:02 Quote from: andyH on February 09, 2021, 03:48:49 pmwith GetItems defined as: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function TBirdList.GetItems(aIndex: Integer): TBird;begin     result:= TBird(self[aIndex]); //results in a exception class 'External: SIGSEGV'.end; With the default in place this will lead to infinite recursion (and thus to a stack overflow), because the default property of your Self is again your Items property. You need to use TBird(inherited Items[aIndex]). ---------------------------------------------------------------------- Bart · 2021-02-10 10:53 Or (assuming the parent class has a GetItems() method which can be overloaded): Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   Result := TBird(inherited GetItems(Index)); (Basically the same, but to me it make more sense to call the inherited method, not the inherited property.) Bart ---------------------------------------------------------------------- PascalDragon · 2021-02-10 12:25 Quote from: Bart on February 10, 2021, 11:53:58 amOr (assuming the parent class has a GetItems() method which can be overloaded): Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   Result := TBird(inherited GetItems(Index)); In case of TList or TObjectList it would be Get and Put. Quote from: Bart on February 10, 2021, 11:53:58 am(Basically the same, but to me it make more sense to call the inherited method, not the inherited property.) That only works as long as the getter (and setter) is not declared as private and while for TList it's indeed declared as protected (due to how the functions are also used by TObjectList), I personally put getters/setters into a private section however (cause for accesses there's the property). ---------------------------------------------------------------------- andyH · 2021-02-10 16:21 Sorted, read and write and nested Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   writeln('bird 0, colour =',Mybirds[0].Species[0].colour);  Mybirds[0].Species[0].colour:= 'yellow';thanks to all. Onto the next problem...