TList
and TOjectList
in Generics.Collections
have a .List
property, which is an enumerator.
For instance:
oList := TObjectList<TItem>.Create;
// Add items to oList
for Item in oList.List do begin
// Do something with Item
end;
This is neat, but has a drastic consequence. .List
just reads FList
(a private declaration on TList
and TObjectList
), which is merely an arrayofT
.
Since a dynamic array is doubled in size whenever an item is added beyond its size, it means it has space for non-used items.
In case you have added 3 TItem
s, the actual FList
is 4 items long, with the fourth (and last) item being nil
.
Thus using TObjectList
's .List
is unsafe, because it will likely throw an access violation, if your TObjectList
doesn't have a .Count
value with a power of 2 (e.g. 1, 2, 4, 8, 16, etc.).
The following code could likely throw an access violation:
for Item in oList.List do begin
Writeln(Item.ClassName);
end;
Of course, the safe solution is a simple iteration using .Count
:
for I := 0 to oList.Count - 1 do begin
Item := oList.Items[I];
Writeln(Item.ClassName);
end;
This is just not as pretty as the enumerator. (You can also check if Item
is nil
, of course.)
My questions are thus:
- Why
.List
isn't an actual enumerator? - And does
TList
/TObjectList
have an actual enumerator?
Here is an example from a TForm
(where btn1
simply adds a line and mmo1
is a TMemo
).
procedure TForm2.btn1Click(Sender: TObject);
var
Line: string;
begin
Line := 'Line';
mmo1.Lines.Add(Line);
fList.Add(Line);
mmo1.Lines.Add(Format('Count: %d; Actual length: %d', [fList.Count, Length(fList.List)]));
for Line in fList.List do begin
mmo1.Lines.Add(Format('Found: "%s"', [Line]));
end;
end;
Now, using string
does not throw an access violation. But when I have clicked 3 times, I get the following:
Count: 3; Actual length: 4
Found: "Line"
Found: "Line"
Found: "Line"
Found: ""
.List
part, because it is too far out for me to use a list this way. But you are right. – JensG Mar 28 '14 at 13:21