基于布尔值的排序列表

编程入门 行业动态 更新时间:2024-10-28 19:34:37
本文介绍了基于布尔值的排序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想使用 dart 中的 Comparable 根据布尔值对列表进行排序。我尝试了以下操作,但无法执行。

I want to sort a list based on a boolean using Comparable in dart. I tried the following but was not able to do it.

在列表中,所有 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-第三项-500 应该首先出现,因为它是 true 但它正在打印

3 - Item three - 500 should come first because it is true but it is printing

1 - Item one - 1000 2 - Item two - 2000 3 - Item three - 500

我在做什么错了?

此代码可以直接在此处的飞镖

推荐答案

compareTo 的实现应该是反身,反对称和可传递的。违反这些属性可能会导致不一致的排序结果。

A compareTo implementation should be reflexive, anti-symmetric, and transitive. Violating these properties can give sort results that are not self-consistent.

按照书面规定,您的 compareTo 声称有两个如果 this.isAvailable 为false,则元素总是按排序顺序视为相等。但是如果 other.isAvailable 是真实的怎么办?

As written, your compareTo claims that two elements are always considered "equal" in sort order if this.isAvailable is false. But what about if other.isAvailable is true?

如果实现 compareTo 而不尝试采取捷径:

Your sort should work if you implement compareTo properly without trying to take shortcuts:

int compareTo(Item other) { if (isAvailable == other.isAvailable) { return 0; } else if (isAvailable) { return -1; } return 1; }

更多推荐

基于布尔值的排序列表

本文发布于:2023-10-26 20:46:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531301.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:列表   布尔值

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!