列表中对象的比较



您将看到我正在尝试,当我传递给他三个对象时,他只停留在不重复的对象上,即关于以下内容:

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}

类Persona poraora 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}';
}
}

两个应该相等的对象没有被set实现检测到,那么这里发生了什么?

Set文档给了我们第一个线索:

默认的Set实现LinkedHashSet,如果对象在操作符Object.==上相等,则认为它们不可区分。

==在这里是正确实现的。让我们看看LinkedHashSet对平等是怎么说的:

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

虽然==在您的类中实现,但hashCode不是。这是一个问题,因为我们可以看到,默认的Set实现依赖于它。

幸运的是,Dart 2.14使您的工作非常容易:

int get hashCode => Object.hash(nombre, apellidio);