I have a class
class Controller with EquatableMixin {
final int id;
//... other props
Controller.from(Controller controller) :
id = controller.id,
//... other props assignments
List<Object> props => [
id,
//... other props
];
}
final ctrl1 = Controller(...); // Create ctrl1
final ctrl2 = Controller.from(ctrl1); // Create ctrl2 (actually clonning)
assert(ctrl1.hasCode != ctrl2.hasCode); // triggered!
I expected that ctrl1
and ctrl2
are different objects with different hashCode
s but they have the same hashCode
. Why? How can I be assure that ctrl12
is not pointer to ctrl2
?
A "Hashcode" is a definition. You decide what hashcode your objects have. A hashcode should not be used to find out if two objects are actually the same memory instance.
Obviously two distinct objects can have the same hashcode:
int i = 5;
int x = 5;
They should have the same hashcode, after all, they are the same value. It's still two distinct variables.
A hashcode also says nothing about whether two objects are equal. The only statement it makes is that two objects with different hashcodes are not equal. Two objects of the same hashcode are not equal until you checked whether they are. They might be equal. A hashcode is a way to reduce the number of actual equality checks you have to make, not a way to determine if something actually is equal.