我想使用Comparable
中的布尔值对列表进行排序dart
。我尝试了以下操作,但无法执行。
在列表中,true
应排在列表其余第一位的所有元素应保持原样。
class Item implements Comparable<Item> {
int id;
String name;
int price;
bool isAvailable;
Item({this.id, this.name, this.price, this.isAvailable = false});
@override
int compareTo(Item other) {
if (isAvailable) {
return -1;
}
return 0;
}
}
void main() {
Item item = new Item(id: 1, name: "Item one", price: 1000);
Item item2 = new Item(id: 2, name: "Item two", price: 2000);
Item item3 =
new Item(id: 3, name: "Item three", price: 500, isAvailable: true);
List<Item> items = [item, item2, item3];
items.sort();
items.forEach((Item item) {
print('${item.id} - ${item.name} - ${item.price}');
});
}
这应该打印
3 - Item three - 500
1 - Item one - 1000
2 - Item two - 2000
3 - Item three - 500
应该先来,因为true
它是印刷品
1 - Item one - 1000
2 - Item two - 2000
3 - Item three - 500
我究竟做错了什么?
此代码可以在Dartpad上直接运行
一个compareTo
实现应该是自反,反对称和传递。违反这些属性可能会导致排序结果不一致。
按照书面规定,compareTo
如果两个元素this.isAvailable
为假,则始终将其按排序顺序视为“相等” 。但是,如果other.isAvailable
是真的呢?
如果compareTo
正确实施而不尝试采用快捷方式,则排序应该可以工作:
int compareTo(Item other) {
if (isAvailable == other.isAvailable) {
return 0;
} else if (isAvailable) {
return -1;
}
return 1;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句