Reputation: 8248
I'm trying to construct a Map
object with Set
as keys:
final myObject = <Set<MyType1>, MyType2>{};
I can successfully insert new values in my object
myObject[{myType1}] = myType2;
However, I cannot get back anything from it as 2 sets with the same values won't be consider equal:
{0} == {0}; // <- false
myObject[{myType1}]; // <- null
Is there something built-in that could allow me to use a Map<Set<T>, U>
object?
Upvotes: 1
Views: 627
Reputation: 4870
Unfortunately, it is not possible to extend any of the Set
classes as they only have factory constructors. This would otherwise have been a clean way to implement a set with a custom notion of equality and hashing.
As an alternative, the HashMap
constructor accepts a custom hash and equality function which can be used:
Map<K, V> hashMapDeep<K extends Set, V>() => HashMap(
equals: setEquals,
hashCode: Object.hashAllUnordered,
);
This uses Object.hashAllUnordered
to create an order-independent has of the set and setEquals
from Flutter for the equality comparison.
Upvotes: 0
Reputation: 17617
You may create your own class that wraps a Set with your own equals and hashCode. Then the problem is solved.
A very rough example to demonstrate my idea:
class MySet<T> {
final Set<T> inner;
...
@override
bool equals(other) => setEquals(this, other); // https://api.flutter.dev/flutter/foundation/setEquals.html
@override
int hashCode => ...
}
P.S. The equals/hashCode of a Set is not implemented as whether the contents are the same, because that would be very costly.
Upvotes: 1