void main(){
var x=Object(33);
var y=Object(33);
print(x.hashCode);
print(y.hashCode);
}
class Object{
int a;
Object(this.a);
}
即使兩者都是相同的實體化,它們也具有不同的哈希碼
uj5u.com熱心網友回復:
您可以將下面的代碼復制到飛鏢墊中自行檢查!
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);}
如果您查看hashCode 屬性的 flutter api,您可以找到以下內容:
Object 實作的默認哈希碼僅表示物件的身份,與默認運算子 == 實作相同的方式僅在物件相同時才認為物件相等(請參閱 identityHashCode)。
總之,是的,兩個變數(或在我的示例中全部三個)具有相同的“內容”,但是,只有 x 和 z 是相同的,因為這些變數擁有完全相同的實體。
如果您深入研究上面鏈接的資源(特別是 == 運算子的作業原理),您將發現為什么您的方法適用于 int、String 和 double 型別(而不是您的 CustomObjects)。
注 - 正如您在此處了解到的,如果您正在構建兩個相同的編譯時常量,則會生成一個所謂的規范實體。請參見上面帶有 var a, b, c, d 的示例(改編自 dart 語言教程)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/374039.html
