首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >返回false的两个相同对象的比较

返回false的两个相同对象的比较
EN

Stack Overflow用户
提问于 2022-10-10 18:37:57
回答 1查看 44关注 0票数 1

我有对象列表,我需要查看新对象是否已经在列表中。所以,如果列表包含新对象,它将返回false,即使我打印了列表,它包含一个具有新对象的相同数据的对象--可能没有根据对象内部的数据在对象之间进行比较。解决方案是什么,例如,我有这个类:

代码语言:javascript
复制
class Favorite{
  final Text date;
  final Text time;
  final Text source;
  final Text destination;
  final Text price;

  Favorite(this.date, this.time, this.source, this.destination, this.price);

  // I used this override to print the data inside the object instead of printing 'instance of favorite' to compare the data
  @override
  String toString() {
    return '[$date, $time, $source, $destination, $price]';
  }
}

在其他班级:

代码语言:javascript
复制
List<Favorite> list = [];
Favorite favorite = Favorite(
  Text(Map<String, dynamic>.from(
      snapshot.value as Map)[Consts.pathDateJourney]),
  Text(Map<String, dynamic>.from(
      snapshot.value as Map)[Consts.pathTimeJourney]),
  Text(Map<String, dynamic>.from(
      snapshot.value as Map)[Consts.pathSourceCity]),
  Text(Map<String, dynamic>.from(
      snapshot.value as Map)[Consts.pathDestinationCity]),
  Text(Map<String, dynamic>.from(
      snapshot.value as Map)[Consts.pathPriceJourney]),);
list.add(favorite);
print(list.contains(favorite)); //returning false
print(list[0] == favorite); //returning false

打印列表的输出:

代码语言:javascript
复制
I/flutter (14458): []
I/flutter (14458): [[Text("2022-10-27"), Text("05:00"), Text("Homs"), Text("Hama"), Text("800 $")]]
I/flutter (14458): [[Text("2022-10-27"), Text("05:00"), Text("Homs"), Text("Hama"), Text("800 $")], [Text("2022-10-27"), Text("05:00"), Text("Homs"), Text("Hama"), Text("800 $")]]
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-10 19:04:37

dart语言中的所有对象,除了原始数据类型,如字符串、int和double.不相等,因为没有任何==操作符被重写并设置为它,这还包括列表、映射等集合.

Favorite类即使没有扩展Object类,也是dart中的Object

因此:

代码语言:javascript
复制
Favorite() == Favorite() // false

除非您重写它的==运算符来设置两个对象应该被视为相等的时间,如下所示:

代码语言:javascript
复制
class Favorite {
  final Text date;
  final Text time;
  final Text source;
  final Text destination;
  final Text price;

  Favorite(this.date, this.time, this.source, this.destination, this.price);


@override
bool operator ==(Object other) {
return other is Favorite && date.toString() == other.date.toString();
} 

现在,您刚刚说过,每个具有相同date.toString()date.toString()类都应该是相等的。

您可以在== overriden方法中设置您的相等逻辑。(这只是一个例子)。

所以当你写

代码语言:javascript
复制
    Favorite fav1 = Favorite(/* properties*/);
    Favorite fav2 = Favorite(/* properties*/)
    fav1 == fav2 // true

它会看到他们是否有相同的日期,如果他们是这样的,那就是true,否则就是false

现在你写的算法应该能用。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74019380

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档