基于布尔值的排序列表 [英] sort list based on boolean

查看:155
本文介绍了基于布尔值的排序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 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;
  }

这篇关于基于布尔值的排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆