Like Java and other languages, Delphi supports collections. This support was however only added after Delphi 7. You can find all of the included generic collection classes in the unit Generics.Collections. In this post I’ll show you 2 collectiontypes from the unit which are commonly used. You can use these in your applications to easily manage various types of data.
The TList class is an item collection which uses integer indices as keys for your collectionitems. The TList class allows you to perform any variety of actions on your collections such as inserting, deleting, moving and finding items. The TList class like all collection classes in the unit is a generic class, this means it’s not specific to a certain type, you have to bind it to a certain type while defining the instance of the collection. Any type can be used with these collections including basetypes. Here’s an example that stores and outputs integer values:
program CollectionsTest; {$APPTYPE CONSOLE} uses SysUtils, Generics.Collections; var Items: TList<Integer>; i, l: Integer; begin Items := TList<Integer>.Create; Items.Add(5); Items.Add(9); Items.Add(1); Items.Add(52); Items.Add(24); l := Items.Count; for i := 0 to l - 1 do WriteLn(Items[i]); Items.Free; ReadLn; // Prevent window from closing. end.
The next collection type I would like to discuss is the dictionary. The dictionary collection is the same as a hashmap in Java. It uses hashes and lineair probing to find items, You can use many different types as a key to bind to your data, the most commonly used type for keys are strings. Here’s an example:
program CollectionsTest; {$APPTYPE CONSOLE} uses SysUtils, Generics.Collections; var Items: TDictionary<string, string>; Enum: TDictionary<string, string>.TPairEnumerator; begin Items := TDictionary<string, string>.Create; Items.Add('first', 'item1'); Items.Add('second', 'item2'); Items.Add('third', 'item3'); Enum := Items.GetEnumerator; while Enum.MoveNext do WriteLn('Key: ' + Enum.Current.Key + ' - Value: ' + Enum.Current.Value); Items.Free; ReadLn; // Prevent window from closing. end.
As you can see in this last example, collections also allow you to use various enumerators to access their data in a convenient way. Also take note that the TDictionary type does not keep the stored data in the order it was entered.
where can I FIND or download the Generics.collection.pas/dcu for delphi7