gpt4 book ai didi

Dart:列表删除不删除对象

转载 作者:行者123 更新时间:2023-12-03 02:47:58 26 4
gpt4 key购买 nike

代码在 DartPad如果你需要一个完整的例子(参见 while 循环结束。)

我有一个循环,

Place place = places[0];
while (places.isNotEmpty) {
// Get a list of places within distance (we can travel to)
List reachables = place.getReachables();

// Get the closest reachable place
Place closest = place.getClosest(reachables);

// Remove the current place (ultimately should terminate the loop)
places.remove(place);

// Iterate
place = closest;
}

但它并没有删除 place在倒数第二行。即 places 的长度list 保持不变,使其成为无限循环。怎么了?

最佳答案

这可能是因为列表中的对象与您尝试删除的对象具有不同的 hashCode。

尝试使用此代码,通过比较对象属性来找到正确的对象,然后再删除它:

var item = list.firstWhere((x) => x.property1== myObj.property1 && x.property2== myObj.property2, orElse: () => null);

list.remove(item);

另一种选择是覆盖类中的 == 运算符和 hashCode。
class Class1 {
@override
bool operator==(other) {
if(other is! Class1) {
return false;
}
return property1 == (other as Class1).property1;
}

int _hashCode;
@override
int get hashCode {
if(_hashCode == null) {
_hashCode = property1.hashCode
}
return _hashCode;
}
}

关于Dart:列表删除不删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34349891/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com