Home > Enterprise >  Custom class Set Intersection not working in Dart
Custom class Set Intersection not working in Dart

Time:06-30

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:

{}

CodePudding user response:

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