Is there a HashSet in Delphi?
Asked Answered
F

3

17

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

Flagwaving answered 4/11, 2015 at 18:50 Comment(1)
AFAIK Delphi doesn't includes a HashSet implementation but you can try the Spring4D project which includes a THashSet Christianchristiana
E
15

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.

Enumeration answered 4/11, 2015 at 19:6 Comment(2)
I think looking for a generic set type also entails looking for set operations such as union, intersect and difference. Also, because of the sorted storage constaints, you get these operations in lograithmic time.Phile
@Phile I don't see any requirement for those operations in the question and my own hash set usage seldom requires them. Plenty of usage scenarios don't. Also I don't think there is a constraint that storage must be sorted. It seems like you might be discussing your own scenarios rather than those presented in this question.Enumeration
C
2

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.

Capitalist answered 4/11, 2015 at 19:4 Comment(0)
C
1

There is now a hash set implementation, THashSet, in Delphi 12 Athens. https://docwiki.embarcadero.com/Libraries/Athens/en/System.Generics.Collections.THashSet

Caste answered 9/8, 2024 at 18:40 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.