Is there a HashSet in Delphi?
I know using set can at most hold 255 items. Is there a HashSet in latest Delphi Compiler e.g. XE8, Seattle
The standard collections do not offer a generic set class. Third party collections libraries such as Spring4D do.
You can build a generic set class quite easily on top of TDictionary<K, V>
. A bare bones version might look like this:
type
TSet<T> = class
private
FDict: TDictionary<T, Integer>;
public
constructor Create;
destructor Destroy; override;
function Contains(const Value: T): Boolean;
procedure Include(const Value: T);
procedure Exclude(const Value: T);
end;
....
constructor TSet<T>.Create;
begin
inherited;
FDict := TDictionary<T, Integer>.Create;
end;
destructor TSet<T>.Destroy;
begin
FDict.Free;
inherited;
end;
function TSet<T>.Contains(const Value: T): Boolean;
begin
Result := FDict.ContainsKey(Value);
end;
procedure TSet<T>.Include(const Value: T);
begin
FDict.AddOrSetValue(Value, 0);
end;
procedure TSet<T>.Exclude(const Value: T);
begin
FDict.Remove(Value);
end;
I've not compiled this code, so you may need to fix any mistakes I made. You'll likely want to extend it to be more capable. But hopefully this can show you how to start.
You can use TDictionary
for that. Define the TKey
type parameter to be the thing you want to track. The TValue
type parameter can be anything; you won't be using it. (Perl also lacks a set type, and so convention is to use its hash type in the same manner I'm suggesting here.)
Call ContainsKey
to check membership. Use Add
or AddOrSetValue
to insert; Remove
to delete.
It would be a trivial exercise to write a wrapper that hides the unused TValue
parameter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With