Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a HashSet in Delphi?

Tags:

hashset

delphi

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

like image 534
justyy Avatar asked Nov 04 '15 18:11

justyy


2 Answers

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.

like image 178
David Heffernan Avatar answered Nov 16 '22 04:11

David Heffernan


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.

like image 2
Rob Kennedy Avatar answered Nov 16 '22 02:11

Rob Kennedy