unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
IniFiles; //THashedStringList 来自 IniFiles 单元
var
Hash: THashedStringList;
{ THashedStringList 继承自 TStringList, 只是覆盖了 IndexOf、IndexOfName 两个方法以增加效率;
如果注重效率而不需要太多功能, 可以使用 TStringHash, 它是直接从 TObject 继承的数组链表 }
//建立哈希表
procedure TForm1.FormCreate(Sender: TObject);
var
i: Integer;
begin
Hash := THashedStringList.Create;
for i := 97 to 122 do
begin
Hash.Add(Chr(i) + '=' + IntToStr(i));
end;
ShowMessage(Hash.Text);
{
构建结果:
a=97
b=98
c=99
d=100
e=101
f=102
g=103
h=104
i=105
j=106
k=107
l=108
m=109
n=110
o=111
p=112
q=113
r=114
s=115
t=116
u=117
v=118
w=119
x=120
y=121
z=122
}
end;
//检索哈希表
procedure TForm1.Button1Click(Sender: TObject);
var
i: Integer;
begin
i := Hash.IndexOf('z=122');
ShowMessage(IntToStr(i)); //25
i := Hash.IndexOfName('z');
ShowMessage(IntToStr(i)); //25
end;
//基本操作
procedure TForm1.Button2Click(Sender: TObject);
begin
Hash.Values['a'] := '65'; //赋值
Hash.ValueFromIndex[0] := '65'; //用索引赋值
ShowMessage(Hash.Values['z']); //122, 取值
ShowMessage(Hash.ValueFromIndex[25]);//122, 用索引取值
{其他操作参加 TStringList}
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
Hash.Free;
end;
end.
Delphi 中的哈希表(2): TStringHash
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
IniFiles; //TStringHash 来自 IniFiles 单元
var
Hash: TStringHash;
{ TStringHash 的功能非常简单, 如果需要更多功能应该使用: THashedStringList
TStringHash 与 THashedStringList、TStringList 最大的不同是:
TStringHash 的 Key 必须是 String; Value 必须是 Integer.
如果这不适合你的要求, 建一个 TMyHash 也不是难事 }
//建立哈希表
procedure TForm1.FormCreate(Sender: TObject);
var
i: Integer;
begin
Hash := TStringHash.Create(26); //26 是表的初始大小, 可以省略使用默认值256
for i := 65 to 90 do
begin
Hash.Add(Chr(i),i); //如果表不够大,会自动增加的
end;
end;
//读取
procedure TForm1.Button1Click(Sender: TObject);
var
num: Integer;
begin
num := Hash.ValueOf('Z');
ShowMessage(IntToStr(num)); //90
end;
//修改、删除、清空
procedure TForm1.Button2Click(Sender: TObject);
begin
Hash.Modify('Z',100); //修改
Hash.Remove('A'); //删除
Hash.Clear; //清空
{没了, 就这些功能}
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
Hash.Free;
end;
end.
https://www.cnblogs.com/del/archive/2007/12/18/1003845.html