Interfaces and Collection Classes in Delphi
By Ray Lischner, December 01, 2001
Delphi has been traditionally weak when it comes to collections. Using interfaces, it is now possible to write useful, type-safe collection classes in Delphi. Ray examines an interface-based set of Collection classes and provides a red-black tree implementation as an example.
December 2001/Interfaces and Collection Classes in Delphi
Example 4: The FindNode, Find, and Remove methods of the TrbTree class
function TRbTree.FindNode(const Obj: ICollectible): TRbNode;
var
Compare: Integer;
begin
Result := Root;
while Result <> Leaf do
begin
Compare := Obj.CompareTo(Result.Item);
if Compare < 0 then
Result := Result.Left
else if Compare > 0 then
Result := Result.Right
else
Exit;
end;
end;
function TRbTree.Find(const SearchFor: ICollectible; out Found: ICollectible):
Boolean;
var
Node: TRbNode;
begin
Node := FindNode(SearchFor);
Result := Node <> Leaf;
if Result then
Found := Node.Item;
end;
procedure TRbTree.Remove(const Obj: ICollectible);
var
Node: TRbNode;
begin
Node := FindNode(Obj);
if Node = Leaf then
ItemNotFound(Obj)
else
RemoveNode(Node);
end;