Home > Net >  Both variables have same contents but show different hashcodes,same happens with Lists but it works
Both variables have same contents but show different hashcodes,same happens with Lists but it works

Time:12-05

    void main(){
    var x=Object(33);
    var y=Object(33);
    print(x.hashCode);    
    print(y.hashCode);
              }
    class Object{
    int a;
    Object(this.a);
                }

Both have different hashcodes even if both are same instantiations

CodePudding user response:

You can copy the code below into dart pad to check it on your own!

   void main() {  
  
    var x = MyObject(33); // Instance X
    var y = MyObject(33); // Instance Y
    var z = x;            // Instance X
    print(x.hashCode);  // hashCode: 329225559  
    print(y.hashCode);  // hashCode: 758565612
    print(z.hashCode);  // hashCode: 329225559
    bool result1 =  identical(x, y);
    bool result2 =  identical(x, z);
    print(result1); // false - They are NOT the same instance!
    print(result2); // true - They are the same instance!
  
   var a =  const MyConstantObject(33);
   var b =  const MyConstantObject(33);
   print(a.hashCode); // 479612920
   print(b.hashCode); // 479612920
   bool result3 =  identical(a, b);
   print(result3); // true - They are the same instance!

   var c = const MyConstantObject(33); // Creates a constant
   var d = MyConstantObject(33); // Does NOT create a constant
   print(c.hashCode); // 479612920
   print(d.hashCode); // 837581838
   bool result4 =  identical(c, d);
   print(result4);// false - NOT the same instance!
}
  
class MyObject{int a; MyObject(this.a);}
class MyConstantObject{ final int a ; const MyConstantObject(this.a);}

If you check out the flutter api for the hashCode property you can find out the following:

The default hash code implemented by Object represents only the identity of the object, the same way as the default operator == implementation only considers objects equal if they are identical (see identityHashCode).

In conclusion, yes both variables (or in my example all three) have the same "content", however, only x and z are identical as these variables hold the exact same instance.

If you dive deeper into the resource linked above (esp. in how the == operator works), you will find out why your approach works with int, String and double types (instead of your CustomObjects).

Note - As you can learn here, if you are constructing two identical compile-time constants, it results in a single, so-called canonical instance. See example above with var a, b, c, d (adapted from the dart language tour).

  • Related