Search code examples
delphitlist

Using way multi TList in Delphi XE5


I want to use multi TList in Delphi. For example:

var
 temp1List : TList;
 temp2List : TList;
begin
 temp1List := TList.Create;
 temp2List := TList.Create;
 temp1List.add(temp2List);
end;

I think it is not correct because TList accepts parameter as Pointer value.

Is there way to use multi TList?


Solution

  • Have a look at the Generic TList<T> instead, eg:

    uses
      ..., System.Classes, System.Generics.Collections;
    
    var
      temp1List : System.Generics.Collections.TList<System.Classes.TList>;
      temp2List : System.Classes.TList;
    begin
      temp1List := System.Generics.Collections.TList<System.Classes.TList>.Create;
      temp2List := System.Classes.TList.Create;
      temp1List.Add(temp2List);
      // don't forget to free them when you are done...
      temp1List.Free;
      temp2List.Free;
    end;
    

    Alternatively, since TList is a class type, you can use TObjectList<T> instead, and take advantage of its OwnsObjects feature:

    uses
      ..., System.Classes, System.Generics.Collections;
    
    var
      temp1List : System.Generics.Collections.TObjectList<System.Classes.TList>;
      temp2List : System.Classes.TList;
    begin
      temp1List := System.Generics.Collections.TObjectList<System.Classes.TList>.Create; // takes Ownership by default
      temp2List := System.Classes.TList.Create;
      temp1List.Add(temp2List);
      // don't forget to free them when you are done...
      temp1List.Free; // will free temp2List for you
    end;