TObjectStack和TObjectQueue類
Contnrs單元中最後兩個類是TObjectStack和TObjectQueue類,類的定義如下:
TObjectStack = class(TStack)
public
procedure Push(AObject: TObject);
function Pop: TObject;
function Peek: TObject;
end;
TObjectQueue = class(TQueue)
public
procedure Push(AObject: TObject);
function Pop: TObject;
function Peek: TObject;
end;
這兩個類只是TStack和TQueue 類的簡單擴展,在鏈表中保存的是TObject的對象引用,而不是簡單的指針。
TIntList 類
到目前為止,我們看到的容器類中保存的都是指針或者對象引用(對象引用其實也是一種指針)。
那麼我們能不能在鏈表中保存原生類型,如Integer,Boolean或者Double等呢。下面的我們定義的類TIntList 類就可以在鏈表中保存整數,這裡我們利用了整數和指針都占用4個字節的存儲空間,所以我們可以直接將指針映射為整數。
unit IntList;
interface
uses
Classes;
type
TIntList = class(TList)
protected
function GetItem(Index: Integer): Integer;
procedure SetItem(Index: Integer;
const Value: Integer);
public
function Add(Item: Integer): Integer;
function Extract(Item: Integer): Integer;
function First: Integer;
function IndexOf(Item: Integer): Integer;
procedure Insert(Index, Item: Integer);
function Last: Integer;
function Remove(Item: Integer): Integer;
procedure Sort;
property Items[Index: Integer]: Integer
read GetItem write SetItem; default;
end;
implementation
{ TIntList }
function TIntList.Add(Item: Integer): Integer;
begin
Result := inherited Add(Pointer(Item));
end;
function TIntList.Extract(Item: Integer): Integer;
begin
Result := Integer(inherited Extract(Pointer(Item)));
end;
function TIntList.First: Integer;
begin
Result := Integer(inherited First);
end;
function TIntList.GetItem(Index: Integer): Integer;
begin
Result := Integer(inherited Items[Index]);
end;
function TIntList.IndexOf(Item: Integer): Integer;
begin
Result := inherited IndexOf(Pointer(Item));
end;
procedure TIntList.Insert(Index, Item: Integer);
begin
inherited Insert(Index, Pointer(Item));
end;
function TIntList.Last: Integer;
begin
Result := Integer(inherited Last);
end;
function TIntList.Remove(Item: Integer): Integer;
begin
Result := inherited Remove(Pointer(Item));
end;
procedure TIntList.SetItem(Index: Integer;
const Value: Integer);
begin
inherited Items[Index] := Pointer(Value);
end;
function IntListCompare(Item1, Item2: Pointer): Integer;
begin
if Integer(Item1) < Integer(Item2) then
Result := -1
else if Integer(Item1) > Integer(Item2) then
Result := 1
else
Result := 0;
end;
procedure TIntList.Sort;
begin
inherited Sort(IntListCompare);
end;
end.