---
title: Override hashCode when overriding ==
description: Datadog, the leading service for cloud-scale monitoring.
breadcrumbs: >-
  Docs > Datadog Security > Code Security > Static Code Analysis (SAST) > SAST
  Rules > Override hashCode when overriding ==
---

> For the complete documentation index, see [llms.txt](https://docs.datadoghq.com/llms.txt).

# Override hashCode when overriding ==

{% callout %}
# Important note for users on the following Datadog sites: app.ddog-gov.com, us2.ddog-gov.com

{% alert level="danger" %}
This product is not supported for your selected [Datadog site](https://docs.datadoghq.com/getting_started/site.md). ({% placeholder "user-datadog-site-name" /%}).
{% /alert %}

{% /callout %}

## Metadata{% #metadata %}

**ID:** `dart-code-quality/hash-and-equals`

**Language:** Dart

**Severity:** Warning

**Category:** Code Style

## Description{% #description %}

In Dart, `==` and `hashCode` work as a pair. If two objects are equal, they must produce the same hash code. Overriding only one of them breaks `Map`, `Set`, and other collections that rely on hashing.

When you override `operator ==`, also override `hashCode` using the same fields that determine equality. If you override `hashCode`, make sure `==` is overridden too.

## Non-Compliant Code Examples{% #non-compliant-code-examples %}

```dart
class OnlyEquals {
  final int value;

  OnlyEquals(this.value);

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is OnlyEquals && value == other.value;
}

class OnlyHashCode {
  final String id;

  OnlyHashCode(this.id);

  @override
  int get hashCode => id.hashCode;
}
```

## Compliant Code Examples{% #compliant-code-examples %}

```dart
class Person {
  final String name;

  Person(this.name);

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is Person && name == other.name;

  @override
  int get hashCode => name.hashCode;
}

class Pair {
  final int a;
  final int b;

  Pair(this.a, this.b);

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is Pair && a == other.a && b == other.b;

  @override
  int hashCode => Object.hash(a, b);
}
```
  Seamless integrations. Try Datadog Code SecurityDatadog Code Security 
{% icon name="icon-external-link" /%}
 