自定义类集交叉点在DART中不起作用

发布于 2025-02-12 01:08:01 字数 549 浏览 0 评论 0原文

以下是代码:

   final Set<Item> _set1 = {
      Item(id: 1, name: "carrot"),
      Item(id: 2,name: "apple"),
      Item(id: 3,name: "mango")
   };

  final Set<Item> _set2 = {
     Item(id: 1, name: "carrot"),
   };
  print(_set1.intersection(_set2));

我的班级看起来像这样:

class Item{
  int id;
  String name;
Item({required this.id,required this.name});
}

必需的输出:

{Instance of 'Item'}
//carrot which is common

以上代码出现的输出:

{}

The Following is the code:

   final Set<Item> _set1 = {
      Item(id: 1, name: "carrot"),
      Item(id: 2,name: "apple"),
      Item(id: 3,name: "mango")
   };

  final Set<Item> _set2 = {
     Item(id: 1, name: "carrot"),
   };
  print(_set1.intersection(_set2));

My Class looks like this:

class Item{
  int id;
  String name;
Item({required this.id,required this.name});
}

Required output:

{Instance of 'Item'}
//carrot which is common

Output that came out of above code:

{}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

自控 2025-02-19 01:08:01

DART中的一个文字创建A

linkedhashset的元素必须具有一致的对象。== object.hashcode 实现。这意味着==操作员必须在元素上定义稳定的等价关系(反射性,对称性,及时且随着时间的推移一致),并且hashcode必须相同对于被视为==的对象。

换句话说,您必须覆盖==hashcodeitem类中。

void main() {
  final Set<Item> _set1 = {
    Item(id: 1, name: "carrot"),
    Item(id: 2, name: "apple"),
    Item(id: 3, name: "mango")
  };

  final Set<Item> _set2 = {
    Item(id: 1, name: "carrot"),
  };
  print(_set1.intersection(_set2));
}

class Item {
  int id;
  String name;
  Item({required this.id, required this.name});
  
  // add an implementation for hashCode and ==
  @override
  int get hashCode => Object.hash(id, name);
  
  @override
  operator ==(Object other) =>
      other is Item && id == other.id && name == other.name;
}

A set literal in dart creates a LinkedHashSet, which has the following requirement:

The elements of a LinkedHashSet must have consistent Object.== and Object.hashCode implementations. This means that the == operator must define a stable equivalence relation on the elements (reflexive, symmetric, transitive, and consistent over time), and that hashCode must be the same for objects that are considered equal by ==.

In other words you must override == and hashCode in your Item class.

void main() {
  final Set<Item> _set1 = {
    Item(id: 1, name: "carrot"),
    Item(id: 2, name: "apple"),
    Item(id: 3, name: "mango")
  };

  final Set<Item> _set2 = {
    Item(id: 1, name: "carrot"),
  };
  print(_set1.intersection(_set2));
}

class Item {
  int id;
  String name;
  Item({required this.id, required this.name});
  
  // add an implementation for hashCode and ==
  @override
  int get hashCode => Object.hash(id, name);
  
  @override
  operator ==(Object other) =>
      other is Item && id == other.id && name == other.name;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文