Flutter Set存储自定义对象时 如何保证唯一

在Flutter中,Set和List是两种不同的集合类型,List中存储的元素可以重复,Set中存储的元素不可重复。

如果想在Set中存储自定义对象,需要确保对象的唯一性。

可以通过在自定义类中实现hashCode方法和equals方法来实现。

  • hashCode方法用于返回对象的哈希码,这是一个整数。在自定义类中,需要覆盖hashCode方法以确保相等的对象具有相同的哈希码。

  • equals方法用于比较两个对象是否相等。在自定义类中,需要覆盖equals方法以确保相等的对象返回true

下面是一个示例自定义类Person,它实现了hashCodeequals方法:

dart 复制代码
class Person {
  final String name;
  final int age;

  Person(this.name, this.age);

  @override
  int get hashCode => name.hashCode ^ age.hashCode;

  @override
  bool get equals(other) => other is Person && other.name == name && other.age == age;
}

在这个例子中,我们使用nameage属性来计算哈希码,并在equals方法中比较这两个属性。

这样,如果两个Person对象具有相同的nameage属性,它们将被视为相等的对象。

现在,可以创建一个Set来存储Person对象,并且Set将确保每个对象是唯一的:

dart 复制代码
Set<Person> people = new Set();

people.add(Person('Alice', 25));
people.add(Person('Bob', 30));
people.add(Person('Alice', 25)); 
// 这个重复的对象不会被添加到Set中

people.forEach((person) => print(person)); 
// 输出Set中的每个Person对象

在这个例子中,第三个对象是重复的,因为它与第一个对象具有相同的nameage属性。

Set会自动忽略重复的对象,确保每个对象是唯一的。

相关推荐
liulian091610 小时前
Flutter for OpenHarmony 跨平台开发:单位转换功能实战指南
flutter
千码君201610 小时前
Trae:一些关于flutter和 go前后端开发构建的分享
android·flutter·gradle·android-studio·trae·vibe code
maaath12 小时前
【maaath】Flutter for OpenHarmony 手表配饰应用实战开发
flutter·华为·harmonyos
maaath13 小时前
【maaath】Flutter for OpenHarmony 跨平台计算器应用开发实践
flutter·华为·harmonyos
maaath18 小时前
【maaath】Flutter for OpenHarmony 闹钟时钟应用开发实战
flutter·华为·harmonyos
maaath18 小时前
【maaath】Flutter for OpenHarmony 短信管理应用实战
flutter·华为·harmonyos
maaath19 小时前
【maaath】Flutter for OpenHarmony打造跨平台便签备忘录应用
flutter·华为·harmonyos
千码君201619 小时前
flutter:与Android Studio模拟器的调试分享
android·flutter
xmdy586620 小时前
Flutter+开源鸿蒙实战|智联邻里Day8 Lottie动画集成+url_launcher跳转拨号+个人中心完善+全局UI统一
flutter·开源·harmonyos
liulian09161 天前
Flutter for OpenHarmony 跨平台开发:颜色选择器功能实战指南
flutter