【发布时间】:2022-01-08 17:29:48
【问题描述】:
我想在 Flutter 中创建一个 Map
void main() {
Map<ActivityProject, int> timesheet = Map.identity();
timesheet.putIfAbsent(ActivityProject('activity', 'project'), () => 1);
timesheet.putIfAbsent(ActivityProject('activity', 'project'), () => 2);
timesheet.putIfAbsent(ActivityProject('activity', 'project'), () => 3);
timesheet.entries.forEach((element) {
print("Hashcode: ${element.key.hashCode}" );
print(
"Key: ${element.key.activity}-${element.key.project}, Value: ${element.value}");
});
}
ActivityProject类定义如下
class ActivityProject {
String activity;
String project;
ActivityProject(this.activity, this.project);
@override
bool operator ==(Object other) =>
other is ActivityProject &&
other.activity == activity &&
other.project == project;
@override
int get hashCode => hashValues(activity, project);
}
我已经覆盖了“==”和hashCode,但即使哈希码相同,值也会放在地图中。
输出:
Hashcode: 176486800
Key: activity-project, Value: 1
Hashcode: 176486800
Key: activity-project, Value: 2
Hashcode: 176486800
Key: activity-project, Value: 3
任何建议都将受到高度赞赏。
【问题讨论】:
标签: flutter dart hashmap flutter-web