unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses Generics.Collections, Generics.Defaults;
var
i: Integer;
str: string;
//無參數的建立
procedure TForm1.Button1Click(Sender: TObject);
var
List: TList<Integer>;
begin
List := TList<Integer>.Create();
List.AddRange([11,22,33]);
str := '';
for i in List do str := str + IntToStr(i) + ' ';
ShowMessage(str); {11 22 33 }
List.Free;
end;
//可以基於另一個列表建立
procedure TForm1.Button2Click(Sender: TObject);
var
List,ListTmp: TList<Integer>;
begin
ListTmp := TList<Integer>.Create();
ListTmp.AddRange([1, 2, 3]);
List := TList<Integer>.Create(ListTmp);
str := '';
for i in List do str := str + IntToStr(i) + ' ';
ShowMessage(str); {1 2 3 }
ListTmp.Free;
List.Free;
end;
//可在建立時同時指定排序器
procedure TForm1.Button3Click(Sender: TObject);
var
List: TList<Integer>;
Comparer: IComparer<Integer>;
begin
{建立排序器}
Comparer := TComparer<Integer>.Construct(
function(const n1,n2: Integer): Integer
begin
Result := n2 - n1;
end
);
List := TList<Integer>.Create(Comparer);
List.AddRange([2, 3, 1]);
List.Sort; {會根據建立時指定的排序器排序}
str := '';
for i in List do str := str + IntToStr(i) + ' ';
ShowMessage(str); {3 2 1 }
List.Free;
end;
end.