我想在 Flutter 中創建一個Map<ActivityProject, int>并將 activityProject 唯一地存盤在地圖內。您可以在下面看到一段代碼。
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
任何建議將不勝感激。
uj5u.com熱心網友回復:
這里的問題是您正在使用Map.identity(). 在此處閱讀有關Map<K, V>.identity 建構式的檔案 。
身份映射使用相同的相等性和 identityHashCode 作為鍵的哈希碼,而不是鍵的固有 Object.== 和 Object.hashCode。
根據檔案,用 構造的地圖Map.identity不使用==和hashCode。
你應該像這樣定義你的地圖:
Map<ActivityProject, int> timesheet = {};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/372214.html
上一篇:如果我在我的計算機上本地更改專案名稱,我可以將我的代碼推送到同一個GitHub存盤庫嗎?
下一篇:從串列中洗掉特定專案范圍
