【问题标题】:What does the hash code have to do in this Flutter Redux example在这个 Flutter Redux 示例中哈希码有什么作用
【发布时间】:2020-11-19 18:24:58
【问题描述】:

我在看this example

@immutable
class UserState {
  final bool isLoading;
  final LoginResponse user;

  UserState({
    @required this.isLoading,
    @required this.user,
  });

  factory UserState.initial() {
    return new UserState(isLoading: false, user: null);
  }

  UserState copyWith({bool isLoading, LoginResponse user}) {
    return new UserState(
        isLoading: isLoading ?? this.isLoading, user: user ?? this.user);
  }

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
          other is UserState &&
              runtimeType == other.runtimeType &&
              isLoading == other.isLoading &&
              user == other.user;

  @override
  int get hashCode => isLoading.hashCode ^ user.hashCode;
}

hashCode 与此有什么关系?这有什么用途? (我已经缩短了代码,因为我收到了我发布的大多数代码的 stackoverflow 错误)

谢谢

【问题讨论】:

    标签: flutter redux flutter-redux


    【解决方案1】:

    您在此处看到这一点,因为该类覆盖了 == 运算符。

    当您覆盖== 运算符时,应始终覆盖hashCode。 任何对象的 hashCode 在使用像 HashMap 这样的 Hash 类时或在将列表转换为集合时使用,这也是散列。

    更多信息:

    1. https://medium.com/@ayushpguptaapg/demystifying-and-hashcode-in-dart-2f328d1ab1bc
    2. https://www.geeksforgeeks.org/override-equalsobject-hashcode-method/ 使用 Java 作为编程语言进行了解释,但应该适用于 dart。

    【讨论】:

      猜你喜欢
      • 2013-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-04
      • 1970-01-01
      • 1970-01-01
      • 2019-11-29
      • 2011-08-29
      相关资源
      最近更新 更多