How does a set determine that two objects are equal in dart? -
How does a set determine that two objects are equal in dart? -
i don't understand how set determines when 2 objects equal. more specific, when add
method of set, adds new object, , when doesn't deed new object, because object in set ?
for example, have objects next class:
class action { final function function; final string description; action(this.function, this.description); call() => function(); tostring() => description; }
now think next set contain 2 elements, 2 of them equal:
void main() { set<action> actions = new set() ..add(new action(() => print("a"), "print a")) ..add(new action(() => print("a"), "print a")) ..add(new action(() => print("b"), "print b")); }
but instead, set contains 3 action
objects. see demo. how can create sure equal objects seen equal in set ?
for comprehensive write-up operator==
in dart see http://work.j832.com/2014/05/equality-and-dart.html
it checks if equal a == b
can override ==
operator customize behavior. maintain in mind hashcode
should overridden when ==
operator overridden.
class action { @override bool operator==(other) { // dart ensures operator== isn't called null // if(other == null) { // homecoming false; // } if(other is! action) { homecoming false; } homecoming description == (other action).description; } // hashcode must never alter otherwise value can't // found anymore illustration when used key // in hashmaps hence cache after first creation. // if want combine more values in hashcode creation // see http://stackoverflow.com/a/26648915/217408 // 1 attempt, depending on requirements // different handling might more appropriate. // far aware there no right reply // objects members taking part of hashcode , // equality calculation mutable. // see http://stackoverflow.com/a/27609/217408 int _hashcode; @override int hashcode { if(_hashcode == null) { _hashcode = description.hashcode } homecoming _hashcode; } // when key (description) immutable , // fellow member of key can utilize // int hashcode => description.hashcode }
try @ dartpad
dart
Comments
Post a Comment