Search code examples
delphihashset

Is there a HashSet in 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


Solution

  • 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.