我想使用Comparablein基于布尔值对列表进行排序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}');
});
}
Run Code Online (Sandbox Code Playgroud)
这应该打印
3 - Item three - 500
1 - Item one - 1000
2 - Item two - 2000
Run Code Online (Sandbox Code Playgroud)
3 - Item three - 500应该排在第一位,因为它是,true但它正在打印
1 - Item one - 1000
2 - Item two - 2000
3 - Item three - 500
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
这里代码可以在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;
}
Run Code Online (Sandbox Code Playgroud)