You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Dart中identityHashCode函数对内置类型int不生效?

Dart中identityHashCode与int类型的行为差异原因

文档参考

identityHashCode文档说明

自定义类的正常表现

identityHashCode在自定义Integer类中表现符合预期:

class Integer {
  int num;
  Integer(this.num);

  @override
  int get hashCode {
    return num;
  }

  @override
  bool operator ==(Object other) {
    if(other is Integer && this.num == other.num) {
      return true;
    }

    return false;
  }
}

void main() {
  Integer n1 = Integer(1);
  print(n1.hashCode); // 输出 "1"
  print(identityHashCode(n1)); // 输出类似 "650939380" 的不同数值!
}

这里n1.hashCode返回重写后的自定义值1,identityHashCode(n1)返回对象本身的标识哈希,两者自然不同。

内置int类型的特殊表现

但测试内置int类型时,结果却完全一致:

void main() {
  int n = 1;
  print(n.hashCode); // 输出 "1"
  print(identityHashCode(n)); // 仍输出 "1",与n.hashCode结果一致!
}

核心原因

这是Dart对内置基础类型的特殊设计导致的:

  • 小整数的单例复用:Dart会对-230到230范围内的小整数复用同一个对象实例,不会每次创建新对象。
  • int的hashCode实现:内置int的hashCode本身就直接返回数值本身,而identityHashCode对于单例对象来说,返回的就是该对象的唯一标识哈希——刚好和数值本身重合。
  • 基础类型的特殊优化:Dart对int、String这类基础类型的identityHashCode做了适配,确保当对象的逻辑哈希(hashCode)和标识哈希一致时,直接返回该值,进一步强化了这个结果。

而自定义类的实例是每次创建新对象,你重写的hashCode和对象本身的标识哈希没有关联,所以两者结果不同。


内容的提问来源于stack exchange,提问作者Sherwei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 08:30:35