Dart 重写子类中的hashCode和运算符==
假设我在一个类中有以下代码:Dart 重写子类中的hashCode和运算符==,dart,Dart,假设我在一个类中有以下代码: abstract class ClassA { final int a; final double b; const ClassA(this.a, this.b); @override bool operator ==(Object other) { if (identical(this, other)) return true; if (other is ClassA) { return runtimeType
abstract class ClassA {
final int a;
final double b;
const ClassA(this.a, this.b);
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
if (other is ClassA) {
return runtimeType == other.runtimeType &&
a == other.a &&
b == other.b;
} else {
return false;
}
}
@override
int get hashCode {
var result = 17;
result = 37 * result + a.hashCode;
result = 37 * result + b.hashCode;
return result;
}
}
现在我想创建两个具体的类B和C,如下所示:
class ClassB extends ClassA {
ClassB() : super(0, 0.0);
}
class ClassC extends ClassA {
final int c;
ClassC(this.c) : super(0, 0.0);
}
当然,ClassB
是可以的,因为它只是扩展了ClassA
,而没有引入任何新变量。但是C类的什么呢?有一个新的c参数,所以我应该再次重写hashCode和==吗?像这样:
class ClassC extends ClassA {
final int c;
ClassC(this.c) : super(0, 0.0);
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
if (other is ClassC) {
return runtimeType == other.runtimeType &&
c == other.c &&
super == other;
} else {
return false;
}
}
@override
int get hashCode {
var result = 17;
result = 37 * result + a.hashCode;
result = 37 * result + super.hashCode;
return result;
}
}
请注意我是如何在ClassC
中添加对super的调用的。是
result = 37 * result + super.hashCode;
需要吗?是的,需要。除非两个C值不同的对象因相等而被忽略。此外,C的哈希代码并没有使用所有成员,因此它可能会扭曲基于哈希的数据结构。是的,需要。除非两个C值不同的对象因相等而被忽略。此外,C的哈希代码并没有使用所有的成员,因此它可能会扭曲基于哈希的数据结构。您可以自己解释。为什么
ClassC
不需要自己的operator==
和hashCode
实现?否则,operator==
和hashCode
将如何解释c
的值?你可以自己解释。为什么ClassC
不需要自己的operator==
和hashCode
实现?否则,operator==
和hashCode
如何解释c
的值?