views:

232

answers:

3

I was wondering how to get the number of items stored in a TBucketList. As far as I can see there is only the number of buckets and the bucket array available, so all I can think of is

Count := 0;
for I := 0 to BucketList.BucketCount - 1 do
  Inc (Count, BucketList.Buckets [I].Count);

That does work but it seems odd to me, that I have to iterate through all buckets to find the number of items stored - something that is probably needed very often.

Am I missing another possibility? Or is there a reason why this container class does not provide a Count member like the other containers?

Thanks!

+3  A: 

Libraries are never complete. But you can extend them.

If you need this value often, you can write a class helper for that.

TBucketListHelper = class helper for TBucketList
  function GetCount: Integer;
end;

function TBucketListHelper.GetCount: Integer;
var
  i : Integer;
begin
  Result := 0;
  for I := 0 to BucketCount - 1 do
    Inc (Result, Buckets [I].Count);
end;

You now can use:

BucketList.GetCount

If TBucketListHelper is within scope.

Gamecat
That's exactly what I did. I don't use TBucketList directly but derived my own class from it anyway. I was just wondering if there is another possiblity or any reason why this wasn't implemented. If I call something like HashTable.Count I don't expect it to iterate over perhaps thousands of buckets...
Smasher
+2  A: 

There is no other solution without having to keep a counter in sync with the content.
It's basically a collection of collections.

A: 

Since you are using your own derived class then just increment and decrement a counter on Add and Remove. You could include the loop method as a double check just in case.

Jim McKeeth