【发布时间】:2021-10-21 14:45:36
【问题描述】:
你会看到我正在尝试,当我传递给他三个对象时,他只停留在不重复的对象上,即关于以下内容:
Person p = Person("nombre", "apellido");
Person p2 = Person("nombre", "apellido");
Person p3 = Person("nombre2", "apellido2");
var list = [ p, p2, p3 ];
Set<Persona> set2 = {...list};
var i = 1;
filteredList.forEach((element) {
print("Person " + i.toString() + ": " + element.toString());
i++;
});
它应该返回如下内容:
Person 1: Person{nombre: nombre, apellido: apellido}
Person 3: Person{nombre: nombre2, apellido: apellido2}
现在的 Person 类是这样的:
Person 1: Person{nombre: nombre, apellido: apellido}
Person 2: Person{nombre: nombre, apellido: apellido}
Person 3: Person{nombre: nombre2, apellido: apellido2}
La clase Persona por aora esta tal que asi:
class Person {
String nombre;
String apellido;
Person(this.nombre, this.apellido);
@override
bool operator ==(other) {
return (other is Person)
&& other.nombre == nombre
&& other.apellido == apellido;
}
@override
String toString() {
return 'Person{nombre: $nombre, apellido: $apellido}';
}
}
【问题讨论】:
-
您还需要实现
Person.hashCode属性(例如使用hashValues顶级函数或Object.hashAll方法) -
正如the answer to your earlier question 所解释的,您必须覆盖both
operator ==和hashCode。Set依赖于两者来识别应该被认为是唯一的对象。