繁体   English   中英

自定义类设置交集在 Dart 中不起作用

[英]Custom class Set Intersection not working in Dart

以下是代码:

   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

上述代码的输出:

{}

dart 中的集合文字创建了一个LinkedHashSet ,它具有以下要求:

LinkedHashSet的元素必须具有一致的Object.==Object.hashCode实现。 这意味着==运算符必须在元素上定义稳定的等价关系(自反、对称、传递和随时间一致),并且对于==认为相等的对象, hashCode必须相同。

换句话说,您必须在Item类中覆盖==hashCode

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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM