In Delphi, you can use the Generics.Collections unit to work with generic collections. This unit provides several generic collection classes that you can use in your code, such as TListT, TOrderedListT, and TDictionaryTKey,TValue.
Here is an example of how you can use the TListT class to create a list of integers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
uses Generics.Collections; var List: TListInteger; I: Integer; begin List = TListInteger.Create; try //Add some integers to the list List.Add(10); List.Add(20); List.Add(30); //Iterate through the list and print the values for I in List do WriteLn(I); finally List.Free; end; end. |
The output of this code would be:
1 2 3 |
10 20 30 |
You can also use type parameters other than Integer, such as String, Boolean, or even your own custom types. For example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
type TPerson = class private FName: string; FAge: Integer; public constructor Create(const AName: string; AAge Integer); property Name: string read FName; property Age: Integer read FAge; end; constructor TPerson.Create(const AName: string; AAge Integer); begin inherited Create; FName := AName; FAge := AAge; end; var People: TListTPerson; Person: TPerson; begin People := TListTPerson.Create; try //Add some people to the list People.Add(TPerson.Create(‘John’, 30)); People.Add(TPerson.Create(‘Jane’, 25)); People.Add(TPerson.Create(‘Bob’, 35)); //Iterate through the list and print the names and ages for Person in People do WriteLn(Person.Name, ‘ (‘, Person.Age, ‘ years old)’); finally People.Free; end; end. |
The output of this code would be
1 2 3 |
John (30 years old) Jane (25 years old) Bob (35 years old) |
Leave a Reply