The history of the architecture of this type of TCollection goes all the way back to 1995, when it was introduced in Delphi 1. Its ancestor is the TCollection for objects, not classes, from TurboPascal 5.5 that Freepascal also still supports but has a very different syntax.
This entry is about classes.TCollection, not objects.TCollection.
A TCollection is a base class for initially unordered, but sortable, collections of TCollectionItems.
To use a TCollection, a derived TCollectionItem has to be created
Inheritance
edit- TObject - Base class of all classes.; IFPObserved - Interface implemented by an object that can be observed.
- TPersistent - Base class for streaming system and persistent properties.
- TCollection - Base class to manage collections of named objects.
- TPersistent - Base class for streaming system and persistent properties.
Basics
editTo use this TCollection you basically just derive from TCollectionItem and create a collection by passing the TCollectionItemClass, not an instance, to the TCollection constructor. The collection then knows what Item class it manages. Type safety and type kind is managed with the as operator (or hardcasts, but that is not recommended). A very basic example looks like this:
program basics;
{$mode objfpc}
uses classes;
type
TSomeRecord = class(TCollectionItem)
private
Fvalue:string;
published
property Value:string read Fvalue write FValue;
end;
var
Collection:TCollection;
Item:TSomeRecord;
begin
// pass the type not a class instance to the TCollection constructor
// the collection can then create Item instances of the correct type automatically
// this is a manifestation of the factory pattern
Collection := TCollection.create(TSomeRecord);
// add items using soft casts for the item type
(Collection.Add as TSomeRecord).Value := 'Test 1';
(Collection.Add as TSomeRecord).Value := 'Test 2';
// add items using hard casts for the item type
TSomeRecord(Collection.Add).Value := 'Test 3';
TSomeRecord(Collection.Add).Value := 'Test 4';
// you can iterate over a collection using its default enumerator
// this requires a hardcast to TCollectionItem unless you create
// an enumerator for the Item type
for TCollectionItem(Item) in Collection do writeln(Item.Value);
Collection.Free;
end.
Outputs:
Test 1
Test 2
Test 3
Test 4
That is not very complex once you grasp the syntax. It shows its age, but it works.
There is no simpler way to get around this original syntax.
Frankly, given the limitations of the language at the time, it is brilliant code.
What follows is a little bit more complex but shows clearly how you handle inheritance with collections:
Simple example
editprogram hair;
{$mode objfpc}{$H+}
uses
Classes;
type
{ THairItem }
THairItem = class(TCollectionItem)
private
FLength: integer;
public
constructor Create(ACollection: TCollection); override;
published
property Length: integer read FLength write FLength;
end;
{ THairList }
THairList = class(TCollection)
private
function GetItems(Index: integer): THairItem;
procedure SetItems(Index: integer; AValue: THairItem);
public
constructor Create;
public
function Add: THairItem;
function AddEx(length: integer): THairItem;
property Items[Index: integer]: THairItem read GetItems write SetItems; default;
end;
{ THairItem }
constructor THairItem.Create(ACollection: TCollection);
begin
if Assigned(ACollection) {and (ACollection is THairList)} then
inherited Create(ACollection);
end;
{ THairList }
function THairList.GetItems(Index: integer): THairItem;
begin
Result := THairItem(inherited Items[Index]);
end;
procedure THairList.SetItems(Index: integer; AValue: THairItem);
begin
Items[Index].Assign(AValue);
end;
constructor THairList.Create;
begin
inherited Create(THairItem);
end;
function THairList.Add: THairItem;
begin
Result := inherited Add as THairItem;
end;
function THairList.AddEx(length: integer): THairItem;
begin
Result := inherited Add as THairItem;
Result.Length := length;
end;
var
hairs: THairList;
begin
hairs := THairList.Create;
hairs.AddEx(10);
hairs.Add.Length := 100;
hairs.Delete(0);
writeln(hairs.Count);
hairs.Free;
end.
Streaming
editThis adds a TComponent class that can stream the list loading and saving to resource files (res format). See also Streaming components.
program streaminghair;
{$mode objfpc}{$H+}{$M+}
uses
Classes;// only classes
type
{ THairItem }
THairItem = class(TCollectionItem)
private
FLength: integer;
public
constructor Create(ACollection: TCollection); override;
published
property Length: integer read FLength write FLength;
end;
{ THairList }
THairList = class(TCollection)
private
function GetItems(Index: integer): THairItem;
procedure SetItems(Index: integer; AValue: THairItem);
public
constructor Create;
public
function Add: THairItem;
function AddEx(length: integer): THairItem;
property Items[Index: integer]: THairItem read GetItems write SetItems; default;
end;
{ THairComponent }
THairComponent = class(TComponent)
private
FHairList: THairList;
procedure SetHairList(AValue: THairList);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
public
procedure SaveToFile(AFileName: string);
procedure LoadFromFile(AFileName: string);
published
property HairList: THairList read FHairList write SetHairList;
end;
{ THairComponent }
constructor THairComponent.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FHairList := THairList.Create;
end;
destructor THairComponent.Destroy;
begin
FHairList.Free;
inherited Destroy;
end;
procedure THairComponent.SetHairList(AValue: THairList);
begin
FHairList.Assign(AValue);
end;
procedure THairComponent.SaveToFile(AFileName: string);
var
AStream: TFileStream;
begin
AStream := TFileStream.Create(AFilename, fmCreate or fmOpenWrite);
try
AStream.WriteComponentres(AFilename,Self);
finally
AStream.Free;
end;
end;
procedure THairComponent.LoadFromFile(AFileName: string);
var
AStream: TFileStream;
begin
AStream := TFileStream.Create(AFilename, fmOpenRead);
try
AStream.ReadComponentres(Self);
finally
AStream.Free;
end;
end;
{ THairItem }
constructor THairItem.Create(ACollection: TCollection);
begin
inherited Create(ACollection);
end;
{ THairList }
function THairList.GetItems(Index: integer): THairItem;
begin
Result := THairItem(inherited Items[Index]);
end;
procedure THairList.SetItems(Index: integer; AValue: THairItem);
begin
Items[Index].Assign(AValue);
end;
constructor THairList.Create;
begin
inherited Create(THairItem);
end;
function THairList.Add: THairItem;
begin
Result := inherited Add as THairItem;
end;
function THairList.AddEx(length: integer): THairItem;
begin
Result := inherited Add as THairItem;
Result.Length := length;
end;
var
hairs: THairComponent;
hair: THairItem;
begin
// optional for use in the ide
// RegisterClass(THairlist);
// RegisterClass(THairItem);
// RegisterComponents('Demo',[THaircomponent]);
hairs := THairComponent.Create(nil);
hairs.HairList.AddEx(10);
hairs.HairList.AddEx(20);
hairs.HairList.AddEx(30);
hairs.SaveToFile('haircomponent.res');
hairs.HairList.Delete(2);
hairs.HairList.Delete(1);
hairs.HairList.Delete(0);
// kill the component
Hairs.free;
Hairs := nil;
// and recreate it
hairs := THairComponent.Create(nil);
hairs.LoadFromFile('haircomponent.res');
for TCollectionItem(hair) in hairs.Hairlist do
writeln('length of item ', Hair.ID, ' hair is ',hair.Length);
readln;
hairs.Free;
end.
Output:
length of item 0 hair is 10
length of item 1 hair is 20
length of item 2 hair is 30
Enumerators
editCollections already have a default enumerator, but as we showed in Basics this requires casts to use it. Enumerators are easy to write so if you want to avoid casts, simply add an enumerator for the Item type. The collection must implement GetEnumerator and the Enumerator must implement GetCurrent and MoveNext. That is all:
program enumerators;
{$ifdef fpc}{$mode objfpc}{$modeswitch advancedrecords}{$endif}{$H-}
uses classes;
type
// forward. We define them later
TStringCollection = class;
TStringItem = class;
// define the string enumerator record
TStringEnumerator = record
private
FCollection: TStringCollection;
FPosition: Integer;
function GetCurrent: TStringItem;
public
constructor Create(ACollection: TStringCollection);
function MoveNext: Boolean;
property Current: TStringItem read GetCurrent;
end;
// a simple TCollectionItem for string values
TStringItem = class(TCollectionItem)
private
FField:string;
published
property value:string read FField write FField;
end;
// a simple TCollection for a string items
TStringCollection = class(TCollection)
private
function GetItem(Index:integer):TStringItem;
procedure SetItem(Index:integer;Item:TStringItem);
public
constructor create;
// this will create and get the TStringEnumerator
function GetEnumerator: TStringEnumerator;
function Add:TStringItem;
property Items[Index:integer]:TStringItem read GetItem write SetItem;default;
end;
constructor TStringEnumerator.Create(ACollection: TStringCollection);
begin
FCollection := ACollection;
FPosition := -1;
end;
function TStringEnumerator.GetCurrent: TStringItem;
begin
Result := FCollection.Items[FPosition];
end;
function TStringEnumerator.MoveNext: Boolean;
begin
Inc(FPosition);
Result := FPosition < FCollection.Count;
end;
constructor TStringCollection.Create;
begin
inherited create(TStringItem);
end;
function TStringCollection.GetItem(Index:integer):TStringItem;
begin
Result := TStringItem(inherited GetItem(index));
end;
procedure TStringCollection.SetItem(Index:integer;Item:TStringItem);
begin
inherited SetItem(Index,Item)
end;
function TStringCollection.GetEnumerator:TStringEnumerator;
begin
Result := TStringEnumerator.Create(Self);
end;
function TStringCollection.Add:TStringItem;
begin
Result := inherited add as TStringItem;
end;
// demo
var
Collection:TStringCollection;
Item:TStringItem;
begin
Collection := TStringCollection.Create;
writeln('This collection contains items of type ',Collection.ItemClass.Classname);
Collection.Add.Value := 'Item 1';
Collection.Add.Value := 'Item 2';
Collection.Add.Value := 'Item 3';
// this uses our new enumerator. Casts are no longer needed.
for Item in Collection do writeln(Item.value);
Collection.free;
end.
You can also declare external enumerators for a collection, so you can do all kinds of strange things with the collection. An external enumerator is basically a simple record that implements both GetEnumerator and the enumerator itself:
type
TEnumReversed = record
private
FOwner: TStringCollection;
FListIndex: integer;
public
constructor Create(owner: TStringCollection);
function GetEnumerator:TEnumReversed;
function GetCurrent: TStringItem;
function MoveNext: boolean;
property Current: TStringItem read GetCurrent;
end;
function TEnumReversed.GetEnumerator:TEnumReversed;
begin
Result := Self;
end;
constructor TEnumReversed.Create(owner: TStringCollection);
begin
FOwner := owner;
FListIndex := owner.Count;
end;
function TEnumReversed.GetCurrent: TStringItem;
begin
Result := FOwner.Items[FListIndex];
end;
function TEnumReversed.MoveNext: boolean;
begin
Result := FListIndex > 0;
if Result then
Dec(FListIndex);
end;
You can add that to the enumerators example and then use it like this:
// demo external enum
var
Collection:TStringCollection;
Item:TStringItem;
Enum:TEnumReversed;
begin
Collection := TStringCollection.Create;
writeln('This collection contains items of type ',Collection.ItemClass.Classname);
Collection.Add.Value := 'Item 1';
Collection.Add.Value := 'Item 2';
Collection.Add.Value := 'Item 3';
// this uses our new external enumerator
// The enum record holds the collection
Enum := TEnumReversed.Create(Collection);
for Item in enum do writeln(Item.Value);
Collection.free;
end.
Sorting a collection
editA Collection has a Sort method with the following signature
type
TCollectionSortCompare = function(Item1,Item2: TCollectionItem):Integer;
Let's add sorting to the enumerators example in three ways. For that we define three different sort functions. Because the sort function expects TCollectionItem we can not use our TStringItem unless we overload TCollection.Sort. Add these three function to the enumerators program and also change the demo code:
function SortStringItems(Item1,Item2: TCollectionItem):Integer;
begin
Result := ShortCompareText(TStringItem(Item1).Value,TStringItem(Item2).Value);
end;
function SortStringItemsReversed(Item1,Item2: TCollectionItem):Integer;
begin
Result := ShortCompareText(TStringItem(Item2).Value,TStringItem(Item1).Value);
end;
function SortItemIds(Item1,Item2: TCollectionItem):Integer;
begin
Result := 0;
If Item1.ID < Item2.ID then result := -1 else If Item1.ID > Item2.ID then Result := 1;
end;
// demo
var
Collection:TStringCollection;
Item:TStringItem;
begin
Collection := TStringCollection.Create;
writeln('This collection items of type ',Collection.ItemClass.Classname);
Collection.Add.Value := 'Test 1';
Collection.Add.Value := 'Test 3';
Collection.Add.Value := 'Test 2';
Collection.Sort(@SortStringItemsReversed);
writeln('Sort in reversed order');
for Item in Collection do writeln(Item.value);
writeln('Sort in order');
Collection.Sort(@SortStringItems);
for Item in Collection do writeln(Item.value);
Collection.Sort(@SortItemIds);
writeln('Sort on item id');
for Item in Collection do writeln(Item.value);
Collection.free;
end.
Notifications
editThis feature is not Delphi compatible, but unique to Freepascal.
TCollection supports the Observer pattern by default and that may be very handy is some use cases.
For this to work, you simply create an Observer class and connect it to the Collection.
- The FPO observer interfaces in Classes are CORBA-style interfaces.({$INTERFACES CORBA}) and are not reference-counted: The observed object does not own the observer. Create and free the observer yourself, and detach it explicitly if the observer may be destroyed before the observed collection.
Suppose we want to add an observer to the basics example. That is as easy as:
{$mode objfpc}
uses classes;
type
TCollectionObserver = class(TInterfacedObject, IFPObserver)
public
procedure FPOObservedChanged(ASender: TObject;
Operation: TFPObservedOperation;
Data: Pointer
);
end;
TMyItem = class(TCollectionItem)
private
FField:string;
published
property Field:string read FField write FField;
end;
procedure TCollectionObserver.FPOObservedChanged(
ASender: TObject;Operation: TFPObservedOperation;Data: Pointer);
var
Item: TCollectionItem;
begin
Item := TCollectionItem(Data);
case Operation of
ooAddItem:Writeln('Item ',Item.ID,' added to the collection');
ooDeleteItem:Writeln('Item ',Item.ID,' deleted from the collection');
ooChange:
begin
if Assigned(Item) then
Writeln('collection changed: item #', Item.Index,
' = ', Item.DisplayName)
else
Writeln('collection changed');
end;
ooFree:Writeln('observed collection is being freed');
else
Writeln(Operation);
end;
end;
var
Observer:TCollectionObserver;
Collection:TCollection;
Item:TMyItem;
begin
// create an observer
Observer := TCollectionObserver.Create;
// pass the TCollectionItemClass
Collection := TCollection.Create(TMyItem);
// Attach the observer
Collection.FPOAttachObserver(Observer as TCollectionObserver);
// store and verify the type
Item := Collection.Add as TMyItem;
// assign a value to the already stored item
Item.Field := 'Test';
// reset the item, does not harm the previously stored
Item := nil;
// get the item back from the collection and verify its type
Item := Collection.Items[0] as TMyItem;
// write its value field
writeln(Item.Field);
// delete the item, just to get a notification
Collection.Delete(0);// fires two times: for extraction and deletion
// and free the collection
Collection.free;
Observer.Free;
end.
This outputs:
Item 0 added to the collection
collection changed
Test
Item 0 deleted from the collection
Item 0 deleted from the collection
collection changed
observed collection is being freed
You will be notified when an Item is added, deleted or changed and when the observer is removed or free'd. There is also a custom notification that you can use for the non-standard ones. Let's wrap that up in an easy to use class:
{$mode objfpc}
uses classes;
type
TCollectionObserver = class(TInterfacedObject, IFPObserver)
private
FOnAddItem,
FOnDeleteItem,
FOnChangeItem,
FOnFreeCollection,
FOnCustomNotification:TNotifyEvent;
public
procedure FPOObservedChanged(ASender: TObject;
Operation: TFPObservedOperation;
Data: Pointer
);
property OnAddItem:TNotifyEvent read FOnAddItem write FOnAddItem;
property OnDeleteItem:TNotifyEvent read FOnDeleteItem write FOnDeleteItem;
property OnChangeItem:TNotifyEvent read FOnChangeItem write FOnChangeItem;
property OnFreeCollection:TNotifyEvent read FOnFreeCollection write FOnFreeCollection;
property OnCustomNotification:TNotifyEvent read FOnCustomNotification write FOnCustomNotification;
end;
procedure TCollectionObserver.FPOObservedChanged(
ASender: TObject;Operation: TFPObservedOperation;Data: Pointer);
var
Item: TCollectionItem;
begin
Item := TCollectionItem(Data);
case Operation of
ooAddItem:if Assigned(FOnAddItem) then FOnAddItem(self);
ooDeleteItem:if Assigned(FOnDeleteItem) then FOnDeleteItem(self);
ooChange:if Assigned(FOnChangeItem) then FOnChangeItem(self);
ooFree:if Assigned(FOnFreeCollection) then FOnFreeCollection(self);
ooCustom:if Assigned(FOnCustomNotification) then FOnCustomNotification(self);
end;
end;
This class can also be used for other classes that support observers, like TStringlist.
Generics
editThe following unit implements a generic collection plus a generic enumerator, so you can use e.g. for..in..do.. without extra work.
It also has a generic collection component, when specialized it registers in the Lazarus IDE when you register the component, the collection and the collection item.
It makes properly typed collections very simple. Not more than:
type
// some data type
TPerson = record name,surname:string[50];end;
// declare item type and collection
TPersonCollectionItem = TGenericCollectionItem<TPerson>;
TPersonCollection = TGenericCollection<TPerson>;
There are five demos, increasingly advanced.
But first the unit:
generic collection unit
editunit gencollection;
{
This unit implements a generic collection
including an automatic generic enumerator.
It also includes a TGenericCollectionComponent,
when specialized you can register the specialization.
This unit is Delphi compatible but written from scratch in FreePascal.
}
{$ifdef fpc}{$mode delphi}{$endif}{$M+}
interface
uses classes;
type
TGenericCollectionItem<T> = class(TCollectionItem)
private
FItem: T;
public
property Value: T read FItem write FItem stored true;
end;
TGenericCollectionEnumerator<T> = class
private
FCollection: TCollection;
FPosition: Integer;
protected
function GetCurrent: TGenericCollectionItem<T>;virtual;
public
constructor Create(ACollection: TCollection);// avoids forward
function MoveNext: Boolean;
property Current: TGenericCollectionItem<T> read GetCurrent;
end;
TGenericCollection<T> = class(TCollection)
protected
Function GetItem(index:integer):TGenericCollectionItem<T>;
procedure SetItem(Index:integer;Item:TGenericCollectionItem<T>);
public
constructor Create;
function Add: TGenericCollectionItem<T>;
function GetEnumerator: TGenericCollectionEnumerator<T>;
property Items[Index:integer]:TGenericCollectionItem<T> read GetItem write SetItem;default;
end;
TGenericCollectionComponent<T>=class(TComponent)
private
FCollection:TGenericCollection<T>;
public
Constructor Create(Owner:TComponent);override;
Destructor Destroy;override;
published
property Collection:TGenericCollection<T> read FCollection;
end;
implementation
function TGenericCollection<T>.GetItem(Index:integer):TGenericCollectionItem<T>;
begin
Result := TGenericCollectionItem<T>(inherited GetItem(index));
end;
procedure TGenericCollection<T>.SetItem(Index:integer;Item:TGenericCollectionItem<T>);
begin
inherited SetItem(Index,Item)
end;
constructor TGenericCollection<T>.Create;
begin
inherited Create(TGenericCollectionItem<T>);
end;
function TGenericCollection<T>.Add: TGenericCollectionItem<T>;
begin
Result := TGenericCollectionItem<T>(inherited Add);
end;
function TGenericCollection<T>.GetEnumerator:TGenericCollectionEnumerator<T>;
begin
Result := TGenericCollectionEnumerator<T>.Create(self);
end;
constructor TGenericCollectionEnumerator<T>.Create(ACollection: TCollection);
begin
inherited Create;
FCollection := ACollection;
FPosition := -1;
end;
function TGenericCollectionEnumerator<T>.GetCurrent: TGenericCollectionItem<T>;
begin
Result := TGenericCollectionItem<T>(FCollection.Items[FPosition])
end;
function TGenericCollectionEnumerator<T>.MoveNext: Boolean;
begin
Inc(FPosition);
Result := FPosition < FCollection.Count;
end;
Constructor TGenericCollectionComponent<T>.Create(Owner:TComponent);
begin
inherited Create(Owner);
FCollection := TGenericCollection<T>.Create;
end;
Destructor TGenericCollectionComponent<T>.Destroy;
begin
FCollection.Free;
Inherited Destroy;
end;
end.
demo 1 simplest example
editA simple collection of strings.
In mode ObjFpc:
program simpledemo;
{$ifdef fpc}{$mode objfpc}{$endif}
uses
Classes, GenCollection;
type
// define a custom collection item and a custom collection
TStringItem = specialize TGenericCollectionItem<string>;
TStringCollection = specialize TGenericCollection<string>;
var
StringCollection: TStringCollection;
Item:TStringItem ;
begin
StringCollection := TStringCollection.Create;
try
StringCollection.Add.Value := 'First Item';
StringCollection.Add.Value := 'Second Item';
for Item in StringCollection do // automatic support for for in do
with Item do writeln(Value:10,Id:4);
finally
StringCollection.Free;
end;
readln;
end.
And in mode Delphi:
{$ifdef fpc}{$mode delphi}{$endif}
uses
Classes, GenCollection;
type
// define a custom collection item and a custom collection
TStringItem = TGenericCollectionItem<string>;
TStringCollection = TGenericCollection<string>;
var
StringCollection: TStringCollection;
Item:TStringItem ;
begin
StringCollection := TStringCollection.Create;
try
StringCollection.Add.Value := 'First Item';
StringCollection.Add.Value := 'Second Item';
for Item in StringCollection do // automatic support for for in do
with Item do writeln(Value:10,Id:4);
finally
StringCollection.Free;
end;
readln;
end.
In all other examples, if you prefer mode objfpc, just add specialize to the type declarations.
demo 2 use the component
editA database type collection of records. Also uses a specialization of the generic collection component. Shows how to sort too:
program app;
{$ifdef fpc}{$mode delphi}{$M+}{$endif}
uses
SysUtils, Classes, GenCollection;
type
TPerson = record
Surname,
Name:string[50];
end;
TPersonCollectionItem = TGenericCollectionItem<TPerson>;
TPersonCollection = TGenericCollection<TPerson>;
TPersonsComponent = TGenericCollectionComponent<TPerson>;
function SortName(Item1,Item2: TPersonCollectionItem):Integer;
begin
Result := CompareText(Item1.Value.Name,Item2.Value.Name);
end;
function SortSurname(Item1,Item2: TPersonCollectionItem):Integer;
begin
Result := CompareText(Item1.Value.surname,Item2.Value.surname);
end;
function SortId(Item1,Item2:TPersonCollectionItem):integer;
begin
if Item1.Id < Item2.Id then result := -1 else
if Item2.Id < Item1.Id then result := 1 else
Result := 0;
end;
var
Person:TPerson;
Persons:TPersonCollection;
PersonItem: TPersonCollectionItem;
C:TPersonsComponent;
begin
C := TPersonsComponent.Create(nil);
Persons := C.Collection;
try
Person := Default(TPerson);
Person.name := 'John';
Person.Surname := 'Doe';
Persons.Add.Value := Person;
Person.Name := 'Fred';
Person.Surname := 'Flintstone';
Persons.Add.Value := Person;
Person.Name := 'Wilma';
Person.Surname := 'Flintstone';
Persons.Add.Value := Person;
Person.Name := 'Jane';
Person.Surname := 'Doe';
Persons.Add.Value := Person;
Persons.Sort(@SortSurname);
for PersonItem in Persons do
writeln('Sort on Surname: ',PersonItem.Value.Surname:12,PersonItem.Value.name:12,PersonItem.Id:2);
Persons.Sort(@SortName);
for PersonItem in Persons do
writeln('Sort on name: ',PersonItem.Value.Surname:12,PersonItem.Value.name:12,PersonItem.Id:2);
Persons.Sort(@SortId);
for PersonItem in Persons do
writeln('Sort on ID: ',PersonItem.Value.Surname:12,PersonItem.Value.name:12,PersonItem.Id:2);
finally
C.Free;
end;
readln;
end.
Outputs:
Sort on Surname: Doe Jane 3
Sort on Surname: Doe John 0
Sort on Surname: Flintstone Fred 1
Sort on Surname: Flintstone Wilma 2
Sort on name: Flintstone Fred 1
Sort on name: Doe Jane 3
Sort on name: Doe John 0
Sort on name: Flintstone Wilma 2
Sort on ID: Doe John 0
Sort on ID: Flintstone Fred 1
Sort on ID: Flintstone Wilma 2
Sort on ID: Doe Jane 3
demo 3 work with two interacting collections
editThis is based on a previous, working, but incorrect entry.
Demonstrates how to connect two collections, like two tables in a database:
program books;
{$ifdef fpc}{$mode delphi}{$codepage utf8}{$endif}
uses classes, gencollection;
type
{ TBookItem }
TBook = record
Author,
Title: string;
end;
{ TPeopleItem }
TPeople = record
Name:string;
Choice: integer;
end;
{ TBookCollection }
TBookItem = TGenericCollectionItem<TBook>;
TCustomBookCollection = TGenericCollection<TBook>;
TBookCollection = class(TCustomBookCollection)
public
function AddEx(aAuthor, aTitle: string): TBookItem;
end;
{ TPeopleCollection }
TPeopleItem = TGenericCollectionItem<TPeople>;
TCustomPeopleCollection = TGenericCollection<TPeople>;
TPeopleCollection = class(TCustomPeopleCollection)
public
function AddEx(aName:string; aChoice: integer): TPeopleItem;
end;
{ TBookCollection }
function TBookCollection.AddEx(aAuthor, aTitle: string): TBookItem;
var
T:TBook;
begin
T.Author := aAuthor;
T.Title := aTitle;
Result := inherited Add;
Result.Value := T;
end;
{ TPeopleCollection }
function TPeopleCollection.AddEx(aName: string;aChoice: integer): TPeopleItem;
var
T:TPeople;
begin
T.Name := aName;
T.Choice := aChoice;
Result := inherited Add;
Result.Value := T;
end;
function SortAuthor(Item1,Item2: TBookItem):Integer;
begin
Result := ShortCompareText(Item1.Value.Author,Item2.Value.Author);
end;
var
Books:TBookCollection;
BookItem:TBookItem;
People:TPeopleCollection;
PeopleItem:TPeopleItem;
begin
Books := TBookCollection.Create;
People := TPeopleCollection.Create;
try
Books.AddEx('Umberto Eco','The Name of the Rose');
Books.AddEx('Ursula K. Le Guin','The Left Hand of Darkness');
Books.AddEx('Douglas Hofstadter','Gödel, Escher, Bach');
Books.AddEx('Ursula K. Le Guin','The Dispossessed');
Books.Sort(@SortAuthor);
for BookItem in Books do
with BookItem.value do writeln(Author:20,Title:40);
//people who read books:
People.AddEx('Marianne Vos',3);
People.AddEx('Jeroen van Dijk',1);
People.AddEx('Saskia Vermeer',0);
People.AddEx('Tomás Richter',2);
for PeopleItem in People do
with PeopleItem.Value do
begin
BookItem := Books.FindItemID(Choice) as TBookItem;
writeln(Name,' reads ', BookItem.Value.Title);
end;
finally
People.free;
Books.Free;
end;
end.
Outputs:
Douglas Hofstadter Gödel, Escher, Bach
Umberto Eco The Name of the Rose
Ursula K. Le Guin The Dispossessed
Ursula K. Le Guin The Left Hand of Darkness
Marianne Vos reads The Dispossessed
Jeroen van Dijk reads The Left Hand of Darkness
Saskia Vermeer reads The Name of the Rose
Tomás Richter reads Gödel, Escher, Bach
demo 4 use change notifications
editSee also: Notifications (newly added). This part will change in the near future. (but is correct)
TCollection implements the Observer pattern, change notifications, and that is a very powerful but underrated feature.
Here is an example how you use it, based on demo 1.
You basically declare an observer class and attach the observer to the collection.
- The FPO observer interfaces in Classes are CORBA-style interfaces.({$INTERFACES CORBA}) and are not reference-counted: The observed object does not own the observer. Create and free the observer yourself, and detach it explicitly if the observer may be destroyed before the observed collection.
program ObserveCollection;
{$mode delphi}
uses gencollection, classes;
type
TGenericCollectionObserver<T> = class(TInterfacedObject, IFPObserver)
public
procedure FPOObservedChanged(
ASender: TObject;
Operation: TFPObservedOperation;
Data: Pointer
);
end;
// define a custom collection item and a custom collection
TStringItem = TGenericCollectionItem<string>;
TStringCollection = TGenericCollection<string>;
// define an observer for the collection
TStringCollectionObserver = TGenericCollectionObserver<string>;
procedure TGenericCollectionObserver<T>.FPOObservedChanged(
ASender: TObject;Operation: TFPObservedOperation;Data: Pointer);
var
Item: TCollectionItem;
begin
Item := TCollectionItem(Data);
case Operation of
ooAddItem:Writeln('Item ',Item.ID,' added to the collection');
ooDeleteItem:Writeln('Item ',Item.ID,' deleted from the collection');
ooChange:
begin
if Assigned(Item) then
Writeln('collection changed: item #', Item.Index,
' = ', Item.DisplayName)
else
Writeln('collection changed');
end;
ooFree:Writeln('observed collection is being freed');
else
Writeln(Operation);
end;
end;
var
StringCollection: TStringCollection;
Item:TStringItem ;
Observer:TStringCollectionObserver;
begin
Observer := TStringCollectionObserver.Create;
StringCollection := TStringCollection.Create;
try
StringCollection.FPOAttachObserver(Observer);
StringCollection.Add.Value := 'First Item';
StringCollection.Add.Value := 'Second Item';
for Item in StringCollection do // automatic support for for in do
with Item do writeln(Value:10,Id:4);
StringCollection.Delete(1);
for Item in StringCollection do // automatic support for for in do
with Item do writeln(Value:10,Id:4);
finally
// StringCollection.FPODetachObserver(Observer); //see remark above
StringCollection.Free;
Observer.Free;
end;
readln;
end.
Outputs:
Item 0 added to the collection
collection changed
Item 1 added to the collection
collection changed
First Item 0
Second Item 1
Item 1 deleted from the collection
Item 1 deleted from the collection
collection changed
First Item 0
observed collection is being freed
- note the double deletion notification is because that fires on both extraction and deletion, so that is fine.
external generic enumerators unit
editAs we already explained, you can have only one automatic internal enumerator, but we also showed that you can write external enumerators.
A common pattern is reversed traversal of a collection, it is so common that we can make it generic.
This processes the collection in LIFO order.
Another common pattern is stepwise traversal which is also a good candidate for a generic enumerator.
This is a great pattern to split up the data in the collection for use in Threads, e.g.:
// non-overlapping enumerators with steps
data1 := TStepwiseTraversal<string>.Create(Collection,{start}0,{step}3);
data2 := TStepwiseTraversal<string>.Create(Collection,1,3);
data3 := TStepwiseTraversal<string>.Create(Collection,2,3);
Yet another common pattern is a windowed traversal which iterates over only part of a collection.
This is also a great pattern to split up the data in the collection for use in Threads, e.g.:
// non-overlapping enumerators for windowed parts of a collection
data1 := TWindowedTraversal<string>.Create(Collection,{start at}0,{stop after}2);
data2 := TWindowedTraversal<string>.Create(Collection,2,2);
data3 := TWindowedTraversal<string>.Create(Collection,4,2);
Let's put them all in ready to use unit, the unit depends on the gencollection unit we defined before:
unit collectionenumerators;
{$ifdef fpc}{$mode delphi}{$endif}
interface
uses
classes, gencollection;
type
TReverseTraversal<T> = record
private
FCollection: TGenericCollection<T>;
FListIndex: integer;
public
constructor Create(aCollection: TGenericCollection<T>);
function GetEnumerator:TReverseTraversal<T>;
function GetCurrent: TGenericCollectionItem<T>;
function MoveNext: boolean;
property Current: TGenericCollectionItem<T> read GetCurrent;
end;
TStepwiseTraversal<T> = record
private
FCollection: TGenericCollection<T>;
FListIndex: integer;
FStep:Cardinal;
public
constructor Create(aCollection: TGenericCollection<T>;Start,Step:Cardinal);
function GetEnumerator:TStepwiseTraversal<T>;
function GetCurrent: TGenericCollectionItem<T>;
function MoveNext: boolean;
property Current: TGenericCollectionItem<T> read GetCurrent;
end;
TWindowedTraversal<T> = record
private
FCollection: TGenericCollection<T>;
FListIndex: integer;
FStart,
FStop:Cardinal;
public
constructor Create(aCollection: TGenericCollection<T>;start,count:Cardinal);
function GetEnumerator:TWindowedTraversal<T>;
function GetCurrent: TGenericCollectionItem<T>;
function MoveNext: boolean;
property Current: TGenericCollectionItem<T> read GetCurrent;
end;
function localmin(const a,b:integer):integer;
implementation
function TReverseTraversal<T>.GetEnumerator:TReverseTraversal<T>;
begin
Result := Self;
end;
constructor TReverseTraversal<T>.Create(aCollection: TGenericCollection<T>);
begin
FCollection := aCollection;
FListIndex := FCollection.Count;
end;
function TReverseTraversal<T>.GetCurrent: TGenericCollectionItem<T>;
begin
Result := FCollection.Items[FListIndex];
end;
function TReverseTraversal<T>.MoveNext: boolean;
begin
Result := FListIndex > 0;
if Result then
Dec(FListIndex);
end;
function TStepwiseTraversal<T>.GetEnumerator:TStepwiseTraversal<T>;
begin
Result := Self;
end;
constructor TStepwiseTraversal<T>.Create(aCollection: TGenericCollection<T>;Start,Step:Cardinal);
begin
FCollection := aCollection;
FStep := Step;
FListIndex := -step + start;
end;
function TStepwiseTraversal<T>.GetCurrent: TGenericCollectionItem<T>;
begin
Result := FCollection.Items[FListIndex];
end;
function TStepwiseTraversal<T>.MoveNext: boolean;
begin
Inc(FListIndex,FStep);
Result := FListIndex < FCollection.Count;
end;
function TWindowedTraversal<T>.GetEnumerator:TWindowedTraversal<T>;
begin
Result := Self;
end;
constructor TWindowedTraversal<T>.Create(aCollection: TGenericCollection<T>;Start,count:Cardinal);
begin
FCollection := aCollection;
Fstart := Start;
FListIndex := Fstart-1;
FStop := FListIndex+count+1;
end;
function TWindowedTraversal<T>.GetCurrent: TGenericCollectionItem<T>;
begin
Result := FCollection.Items[FListIndex];
end;
function localmin(const a,b:integer):integer;
begin
Result := a;
if b < a then result := b;
end;
function TWindowedTraversal<T>.MoveNext: boolean;
begin
Inc(FListIndex);
Result := FListIndex < localmin(Fcollection.Count, Fstop);
end;
end.
Demo 5, use external enumerators for generic collections
editAnd a demo:
program externalenumerators;
{$apptype console}
{$ifdef fpc}{$mode delphi}{$endif}
uses
gencollection, collectionenumerators;
type
// define a string collection item and a string collection
TStringItem = TGenericCollectionItem<string>;
TStringCollection = TGenericCollection<string>;
var
C:TStringCollection;
Reverse: TReverseTraversal<string>;
Steps:TStepwiseTraversal<string>;
Parts:TWindowedTraversal<string>;
item:TStringItem;
begin
C := TStringCollection.Create;
C.Add.Value := 'Item 1';C.Add.Value := 'Item 2';C.Add.Value := 'Item 3';
C.Add.Value := 'Item 4';C.Add.Value := 'Item 5';C.Add.Value := 'Item 6';
writeln(stringOfChar('_',28),'write standard',stringOfChar('_',6));
for Item in C do write(Item.Value:8);
writeln;
Reverse := Reverse.Create(C); // it is a record!
writeln(stringOfChar('_',28),'write reversed',stringOfChar('_',6));
for Item in Reverse do write(Item.value:8);
writeln;
writeln(stringOfChar('_',28),'write odds',stringOfChar('_',10));
Steps := Steps.Create(C,0,2);
for Item in Steps do write(Item.value:8);writeln;
writeln(stringOfChar('_',28),'write evens',stringOfChar('_',9));
Steps := Steps.Create(C,1,2);
for Item in Steps do write(Item.value:8);writeln;
writeln(stringOfChar('_',28),'start 0, step 3',stringOfChar('_',5));
Steps := Steps.Create(C,0,3);
for Item in Steps do write(Item.value:8);writeln;
writeln(stringOfChar('_',28),'start 1, step 3',stringOfChar('_',5));
Steps := Steps.Create(C,1,3);
for Item in Steps do write(Item.value:8);writeln;
writeln(stringOfChar('_',28),'start 2, step 3',stringOfChar('_',5));
Steps := Steps.Create(C,2,3);
for Item in Steps do write(Item.value:8);writeln;
Parts := Parts.Create(C,0,2);
writeln(stringOfChar('_',28),'starts 0, count 2',stringOfChar('_',5));
for Item in parts do write(item.Value:8);writeln;
Parts := Parts.Create(C,2,2);
writeln(stringOfChar('_',28),'starts 2, count 2',stringOfChar('_',5));
for Item in parts do write(item.Value:8);writeln;
Parts := Parts.Create(C,4,2);
writeln(stringOfChar('_',28),'starts 4, count 2',stringOfChar('_',5));
for Item in parts do write(item.Value:8);writeln;
C.free;
readln;
end.
Some remarks:
editCollections derived from TCollection only have an advantage over something like a TList<T> in at least five ways:
- They are streamable by default since they inherit from TPersistent
- Specializations will show up in the object inspector because of that
- They have built-in change notifications
- They have a unique, persistent, Item ID, not just an index value. A light weight database table.
- And have full RTTI automatically