Programming Search⌘K

Conceptcore

Equality and identity

Also called value equality, reference equality, object identity, structural equality, sameness.

Two values are equal when they hold the same data. Two references are identical when they point to the same object. Each language decides which of the two tests its operators make.

Applies to
core-languages

Idea

A program often asks if two values are the same. The question has two meanings. Two values can be equal: they hold the same data, so the program can use one in place of the other. Or two references can be identical: they point to the same object in memory, so a change through one is visible through the other. Two copies of the point (1, 2) are equal and not identical. A second variable that holds the same reference as the first is identical to it, and so also equal.

Each language gives one operator, or two, and decides which question each one asks. The decision is different from language to language, and sometimes from type to type in one language. This is the source of many bugs: a test that compares identity where the programmer meant equality, or the reverse.

from dataclasses import dataclass


@dataclass(frozen=True)
class Point:
    x: int
    y: int


a = Point(1, 2)
b = Point(1, 2)
c = a
print(a == b, a is b)
print(a == c, a is c)
print(len({a, b, c}))
Output
True False
True True
1

In Python, == asks if the values are equal and is asks if the two names refer to the same object.1 a and b are two objects with the same fields, so they are equal and not identical. c is a second name for the object a, so it is both. A set keeps one copy of equal values, so the three names give a set of one element.

How it works

Identity

Identity is a property of objects that live at an address. Two references are identical when they refer to the same object. A language can test this in one step, because it compares two addresses. The test does not depend on the type and needs no code from the programmer.

Identity matters for mutable objects. If a and c are identical, a change made through a is visible through c. If a and b are only equal, a change through a makes them different. Pointers and references shows aliasing in detail.

Some values have no identity that a program can see. In C, an int is a value in a variable, and two variables that hold 3 are two variables. The question "is this the same 3?" has no meaning. Many languages make small immutable values work like this, even when the run time stores them as objects.

Equality

Equality is a question about the data. Its meaning depends on the type, so somebody must define it. There are three common sources of a definition:

  • The language. Numbers, strings in most languages, and structs in Go have a built-in equality.2
  • The compiler, from the fields. A Java record, a C# record, a Python data class, a Kotlin data class and a Rust type with #[derive(PartialEq)] compare their fields in order.34567
  • The programmer, in a method such as equals, Equals, __eq__ or operator==.

When a class defines nothing, most object-oriented languages use identity as the default equality. Python's default __eq__ compares identity, and so do Object.equals in Java and Object.Equals for a C# class.8910 So two objects of a plain class with equal fields are not equal until the class says how to compare them.

The rules of an equality

An equality method must behave like equality in mathematics. The Java documentation of Object.equals gives the rules:9

Rule Meaning
Reflexive x.equals(x) is true.
Symmetric x.equals(y) is true exactly when y.equals(x) is true.
Transitive If x.equals(y) and y.equals(z) are true, x.equals(z) is true.
Consistent Many calls give the same result if no data used in the comparison changes.
Not null x.equals(null) is false.

Collections depend on these rules. A list search, a set and a map key all call the equality of the elements. A method that breaks a rule makes a collection give answers that look random. A common break of symmetry is an equals in a subclass that compares more fields than the equals of its superclass. Then a base object is equal to a derived object, but the derived object is not equal to the base object.

Rust puts the rules in the type system. PartialEq is the trait for ==, and it requires symmetry and transitivity. Eq adds reflexivity.711 Floating point types implement PartialEq and not Eq, because NaN != NaN.7

Equality and hashing

A hash table finds a key in two steps. It computes the hash code of the key and goes to the bucket for that code. Then it compares the key with each entry in the bucket by equality. This only works if equal values have equal hash codes. Python and Java state this rule in their documentation.129

So equality and hashing are one design decision. A class that redefines equality must redefine the hash too, from the same fields. Python enforces part of this: a class that defines __eq__ and not __hash__ gets __hash__ set to None, so its objects cannot be set elements or dictionary keys.12 Java does not enforce it, and a class that overrides only equals gives a HashSet that keeps duplicates. The pitfalls below show both.

A second rule follows. The hash code of a key must not change while the key is in a table. If a program changes a field that equality uses, the table looks in the wrong bucket. Immutable keys avoid the problem. Immutability has more.

Four kinds of sameness

Real languages have more than two tests. JavaScript has four algorithms, and the differences are in the details of numbers:13

Test Converts types NaN and NaN 0 and -0 Used by
== yes not equal equal the loose equality operator
=== no not equal equal ===, indexOf, switch
SameValueZero no equal equal includes, Set, Map
Object.is no equal not equal Object.is

Floating point is the reason for the split. IEEE 754 says that NaN is not equal to any value, itself included, and that 0 equals -0.14 Floating-point arithmetic explains why. This numerical equality is not reflexive, so it cannot serve as the equality of a set. Java solves this with two definitions. The == operator on double follows IEEE 754. Double.equals uses representation equivalence: it treats NaN as equal to NaN and 0.0 as not equal to -0.0, so a Double can be a HashSet element or a HashMap key.14 .NET makes the same choice for Double.Equals.15 Kotlin uses IEEE 754 when the operands are statically known to be floating point numbers, and the equals rule otherwise.6

Python takes a third way. A list, a set and a dictionary test x is e or x == e for each element, so a container finds the same NaN object that it holds, although NaN == NaN is false.16

Equality of composite values

For a composite value, equality is usually defined from the parts: two structs are equal when their fields are equal, and two lists are equal when they have the same length and equal elements in the same order. Go defines == this way for structs and arrays, and it compares the fields in source order and stops at the first difference.2 C++ does the same for a defaulted operator==.17

Not every type has a useful structural equality. Go does not allow == on slices, maps and functions, except a comparison with nil.2 The standard library has slices.Equal and maps.Equal for contents. C does not allow == on structs at all. The operands of == must be numbers or pointers.18 A program must compare the fields one by one, and memcmp is not a correct shortcut, because the padding bytes of a struct have unspecified values.19

Deep equality also has a cost. It visits each part, so the time grows with the size of the value. Identity takes one comparison. Some programs keep one copy of each distinct value, and then compare identity in place of equality. This is called interning or hash consing. The atoms of LISP work this way: two atoms with the same name are the same symbol, so eq can compare them.20

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CIdiom
C#Native
JavaScriptIdiom
TypeScriptIdiom
GoNative
RustNative
KotlinNative== calls equals and handles null, === compares references, and a data class gets equals and hashCode from its properties; no example file because kotlinc is not installed on the machine that recorded the examples. Alternative: Data class for value equality, and === for identity.
SQLNative
BashIdiom
PowerShellNative-eq compares values, and string comparisons are case-insensitive unless the script uses -ceq; no example file because pwsh is not installed on the machine that recorded the examples. Alternative: -ceq for a case-sensitive comparison, and [object]::ReferenceEquals for identity.
HTMLDoes not applyMarkup has no values to compare.
CSSDoes not applyStyle rules have no values to compare.
Regular expressionsDoes not applyA regular expression matches text; it has no values to compare for equality.
Language Value equality Identity Verdict
Python ==, through __eq__ is native
JavaScript a function that the program writes === on objects idiom
TypeScript as JavaScript === on objects idiom
Java equals == on references native
C# == and Equals on records, string and structs ReferenceEquals, and == on plain classes native
Go == on comparable types == on pointers native
Rust ==, through PartialEq std::ptr::eq native
C a function that the program writes == on pointers idiom
C++ operator==, which can be defaulted == on addresses native
Kotlin ==, through equals === native
PowerShell -eq [object]::ReferenceEquals native
Bash == and -eq inside [[ ]] none idiom
SQL =, and IS NOT DISTINCT FROM for NULL none native

Python. == calls __eq__, and is compares identity.81 PEP 8 says to compare with None by is, because None is a single object.8 Python shares some small integers and some strings in CPython, so is on numbers and strings sometimes works by accident. Since Python 3.8 the compiler gives a SyntaxWarning for is with a literal.21

Java. On references, == is identity, also for String.22 equals is value equality when the class overrides it. A record overrides equals and hashCode from its components.3 Boxing converts an int to an Integer object. The language guarantees that boxing gives the same object only for small values, from -128 to 127, so == on boxed numbers works in tests with small numbers and fails later with large ones.2324

C#. A plain class compares references with both == and Equals. A record compares its fields. A struct compares its fields through Equals, but it has no == until it declares one.104 string overloads == with an ordinal, case-sensitive comparison.4 Object.ReferenceEquals always compares references.10 The compiler selects == by the static types, so two boxed int values typed as object compare by reference.

Kotlin. == calls equals and handles null: a == b means a?.equals(b) ?: (b === null). === compares references. A data class gets equals from its properties.6 There is no Kotlin example file, because kotlinc is not installed on the machine that recorded the examples.

JavaScript and TypeScript. === compares primitives by value and objects by identity, and a class cannot change this.13 Value equality of objects is a function, often a comparison of the fields or of a key string. == converts the types of its operands first, and its rules surprise most readers.

Go. == compares values for all comparable types. A struct is comparable if its fields are, and two pointers are equal when they point to the same variable.2 So a struct value compares by value, a pointer compares by identity, and a comparable struct can be a map key with no extra code. Interface values compare their dynamic types and values, and a comparison panics at run time if the dynamic type is not comparable.2

Rust. == calls PartialEq::eq. #[derive(PartialEq, Eq, Hash)] gives field-by-field equality and a matching hash. std::ptr::eq compares two pointers by address.25 A type has no == until it implements PartialEq.

C and C++. In C, == works only on numbers and pointers.18 Two pointers to the same object are equal, so pointer comparison is identity. Strings are arrays of char, and strcmp compares them. In C++, a class can declare operator== as defaulted, and the compiler compares the subobjects in order.17 std::string compares characters, but two const char* operands still compare addresses.

PowerShell. -eq compares values, and string comparisons are case-insensitive unless the script uses -ceq.26 There is no PowerShell example file, because pwsh is not installed on the machine that recorded the examples.

Bash. All values are strings. Inside [[ ]], == matches the left side against a pattern on the right side, and a quoted right side matches as text.27 -eq compares integers.

SQL. = compares values, but a comparison with NULL gives NULL, not true or false. IS NOT DISTINCT FROM treats two NULL values as equal. SQLite also accepts the short form IS.2829 DISTINCT and GROUP BY treat NULL values as equal to each other.30 A row has no identity apart from its key.

PythonGitHub
from dataclasses import dataclass


@dataclass(frozen=True)
class Point:
    x: int
    y: int


class Box:
    def __init__(self, x, y):
        self.x = x
        self.y = y


a = Point(1, 2)
b = Point(1, 2)
c = a
print("a == b:", a == b)
print("a is b:", a is b)
print("a is c:", a is c)
print("distinct points:", len({a, b, c}))

p = Box(1, 2)
q = Box(1, 2)
print("Box p == q:", p == q)

nan = float("nan")
print("nan == nan:", nan == nan)
print("nan in [nan]:", nan in [nan])
print("None is None:", None is None)
Output
a == b: True
a is b: False
a is c: True
distinct points: 1
Box p == q: False
nan == nan: False
nan in [nan]: True
None is None: True
  • Verdict: native. == asks the objects. It calls __eq__, and the default __eq__ compares identity. is compares identity and nothing else.
  • @dataclass(frozen=True) writes __eq__, which compares the fields in order, and __hash__, so a point can go in a set. Box defines neither, so two boxes with the same fields are not equal.
  • nan in [nan] is true although nan == nan is false. A list tests x is e or x == e for each element, so the identity test finds the same NaN object.
  • PEP 8 says to compare with None by is.

This code raises TypeError, on purpose.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __eq__(self, other):
        return isinstance(other, Point) and (self.x, self.y) == (other.x, other.y)


seen = {Point(1, 2)}
print(len(seen))

A class that defines __eq__ and no __hash__ gets __hash__ = None, so its objects cannot go in a set or be dictionary keys. The fix is a __hash__ that hashes the same fields that __eq__ compares, such as hash((self.x, self.y)).

This code runs but gives a wrong answer on purpose.

a = 1000
b = int("1000")
print(a == b)
print(a is b)
Output
True
False

The two values are equal, but they are two objects. CPython shares some small integers, so the same test with 10 can print True. The language does not promise this, and since Python 3.8 the compiler warns about is with a literal. Use == for values and is only for None and other single objects.

#include <cmath>
#include <cstring>
#include <iostream>
#include <set>
#include <string>

struct Point {
    int x;
    int y;
    bool operator==(const Point&) const = default;
    auto operator<=>(const Point&) const = default;
};

int main() {
    Point a{1, 2};
    Point b{1, 2};
    Point* pc = &a;
    std::cout << std::boolalpha;
    std::cout << "a == b: " << (a == b) << "\n";
    std::cout << "&a == &b: " << (&a == &b) << "\n";
    std::cout << "&a == pc: " << (&a == pc) << "\n";
    std::set<Point> points{a, b, *pc};
    std::cout << "distinct points: " << points.size() << "\n";

    std::string s = "hello";
    char buffer[] = "hello";
    const char* literal = "hello";
    std::cout << "s == literal: " << (s == literal) << "\n";
    std::cout << "buffer == literal: " << (buffer == literal) << "\n";
    std::cout << "strcmp(buffer, literal) == 0: " << (std::strcmp(buffer, literal) == 0) << "\n";

    double nan = std::nan("");
    std::cout << "nan == nan: " << (nan == nan) << "\n";
}
Output
a == b: true
&a == &b: false
&a == pc: true
distinct points: 1
s == literal: true
buffer == literal: false
strcmp(buffer, literal) == 0: true
nan == nan: false
  • Verdict: native. A class can declare operator== as defaulted. The defaulted operator compares the subobjects in order and stops at the first pair that is not equal. Comparing addresses with &a == &b is identity.
  • std::string compares characters, also against a const char*. Two const char* or array operands compare addresses.
  • std::set uses <, not ==. Two elements are the same when neither is less than the other. The defaulted <=> gives Point that order.
JavaGitHub
import java.util.HashSet;
import java.util.List;
import java.util.Objects;

public class Main {
    record Point(int x, int y) {}

    static final class Box {
        final int x;
        final int y;

        Box(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }

    public static void main(String[] args) {
        Point a = new Point(1, 2);
        Point b = new Point(1, 2);
        Point c = a;
        System.out.println("a.equals(b): " + a.equals(b));
        System.out.println("a == b: " + (a == b));
        System.out.println("a == c: " + (a == c));
        System.out.println("distinct points: " + new HashSet<>(List.of(a, b, c)).size());

        Box p = new Box(1, 2);
        Box q = new Box(1, 2);
        System.out.println("Box p.equals(q): " + p.equals(q));

        String s = "hello";
        String t = new StringBuilder("hel").append("lo").toString();
        System.out.println("s.equals(t): " + s.equals(t));
        System.out.println("Objects.equals(null, null): " + Objects.equals(null, null));

        double nan = Double.NaN;
        System.out.println("nan == nan: " + (nan == nan));
        System.out.println("Double.valueOf(nan).equals(nan): " + Double.valueOf(nan).equals(nan));
        System.out.println("0.0 == -0.0: " + (0.0 == -0.0));
        System.out.println("Double.valueOf(0.0).equals(-0.0): " + Double.valueOf(0.0).equals(-0.0));
    }
}
Output
a.equals(b): true
a == b: false
a == c: true
distinct points: 1
Box p.equals(q): false
s.equals(t): true
Objects.equals(null, null): true
nan == nan: false
Double.valueOf(nan).equals(nan): true
0.0 == -0.0: true
Double.valueOf(0.0).equals(-0.0): false
  • Verdict: native. On references, == compares identity. equals compares values when the class overrides it. A record overrides equals and hashCode from its components.
  • Object.equals is identity, so Box compares by identity until it overrides equals.
  • Double.equals differs from ==: it treats NaN as equal to NaN and 0.0 as different from -0.0, so a Double works as a HashSet element.
  • Objects.equals handles null on either side.

This code runs but gives a wrong answer on purpose.

public class Main {
    public static void main(String[] args) {
        String s = "hello";
        String t = new StringBuilder("hel").append("lo").toString();
        System.out.println(s == t);
        System.out.println(s.equals(t));
    }
}
Output
false
true

t is a new String object with the same characters. == compares the references, so it is false.

This code runs but gives a wrong answer on purpose.

public class Main {
    public static void main(String[] args) {
        Integer small1 = Integer.valueOf(127);
        Integer small2 = Integer.valueOf(127);
        Integer large1 = Integer.valueOf(128);
        Integer large2 = Integer.valueOf(128);
        System.out.println(small1 == small2);
        System.out.println(large1 == large2);
        System.out.println(large1.equals(large2));
    }
}
Output
true
false
true

Integer.valueOf always caches the values from -128 to 127, so the two 127 objects are the same object. The 128 objects are two objects on this JVM. The result for values outside the cache is not fixed, and a JVM flag can make the cache larger. Compare boxed numbers with equals, or unbox them first.

This code runs but gives a wrong answer on purpose.

import java.util.HashSet;
import java.util.Set;

public class Main {
    static final class Point {
        final int x;
        final int y;

        Point(int x, int y) {
            this.x = x;
            this.y = y;
        }

        @Override
        public boolean equals(Object o) {
            return o instanceof Point p && p.x == x && p.y == y;
        }
    }

    public static void main(String[] args) {
        Set<Point> seen = new HashSet<>();
        seen.add(new Point(1, 2));
        seen.add(new Point(1, 2));
        System.out.println(new Point(1, 2).equals(new Point(1, 2)));
        System.out.println(seen.size());
        System.out.println(seen.contains(new Point(1, 2)));
    }
}
Output
true
2
false

equals says the points are equal, but hashCode is still the one from Object. As far as is reasonably practical, that method returns distinct integers for distinct objects. HashSet looks in the bucket of the hash code first, so it never calls equals on the other point. The fix is a hashCode that uses the same fields, such as Objects.hash(x, y), or a record.

This code runs but gives a wrong answer on purpose.

import java.util.HashSet;
import java.util.Set;

public class Main {
    static final class Point {
        int x;
        int y;

        Point(int x, int y) {
            this.x = x;
            this.y = y;
        }

        @Override
        public boolean equals(Object o) {
            return o instanceof Point p && p.x == x && p.y == y;
        }

        @Override
        public int hashCode() {
            return 31 * x + y;
        }
    }

    public static void main(String[] args) {
        Set<Point> seen = new HashSet<>();
        Point p = new Point(1, 2);
        seen.add(p);
        p.x = 5;
        System.out.println(seen.contains(p));
        System.out.println(seen.size());
        for (Point q : seen) {
            System.out.println(q == p);
        }
    }
}
Output
false
1
true

The set stored p under the hash code of (1, 2). After the change, contains looks under the hash code of (5, 2) and does not find it, although the set holds the same object. Do not change the fields that equals and hashCode use while the object is in a hash set or is a map key. Immutable keys, such as records with final fields, avoid the problem.

#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>

struct point {
    int x;
    int y;
};

static bool point_equal(struct point a, struct point b) {
    return a.x == b.x && a.y == b.y;
}

int main(void) {
    struct point a = {1, 2};
    struct point b = {1, 2};
    struct point *pa = &a;
    struct point *pb = &b;
    struct point *pc = &a;
    printf("point_equal(a, b): %d\n", point_equal(a, b));
    printf("pa == pb: %d\n", pa == pb);
    printf("pa == pc: %d\n", pa == pc);

    char s[] = "hello";
    char t[] = "hello";
    printf("strcmp(s, t) == 0: %d\n", strcmp(s, t) == 0);

    double nan = NAN;
    printf("nan == nan: %d\n", nan == nan);
    return 0;
}
Output
point_equal(a, b): 1
pa == pb: 0
pa == pc: 1
strcmp(s, t) == 0: 1
nan == nan: 0
  • Verdict: idiom. == works on numbers and pointers only. Two pointers are equal when they point to the same object, so == on pointers is identity. A struct needs a comparison function that the program writes, field by field.
  • Strings are arrays of char. strcmp compares the characters. == on two arrays compares their addresses.
  • Do not compare structs with memcmp. The padding bytes of a struct have unspecified values, so two structs with equal fields can have different bytes.

This code does not compile, on purpose.

#include <stdio.h>

struct point {
    int x;
    int y;
};

int main(void) {
    struct point a = {1, 2};
    struct point b = {1, 2};
    printf("%d\n", a == b);
    return 0;
}

The operands of == must be numbers or pointers, so a compiler must reject a comparison of two structs.

This code runs but gives a wrong answer on purpose.

#include <stdio.h>
#include <string.h>

int main(void) {
    char input[16];
    strcpy(input, "quit");
    const char *command = "quit";
    if (input == command) {
        printf("bye\n");
    } else {
        printf("unknown command: %s\n", input);
    }
    return 0;
}
Output
unknown command: quit

input is an array on the stack and command points to a string literal. They are different objects, so == is false although they hold the same characters. Use strcmp(input, command) == 0.

var a = new Point(1, 2);
var b = new Point(1, 2);
var c = a;
Console.WriteLine($"a == b: {a == b}");
Console.WriteLine($"ReferenceEquals(a, b): {ReferenceEquals(a, b)}");
Console.WriteLine($"ReferenceEquals(a, c): {ReferenceEquals(a, c)}");
Console.WriteLine($"distinct points: {new HashSet<Point> { a, b, c }.Count}");

var p = new Box(1, 2);
var q = new Box(1, 2);
Console.WriteLine($"Box p == q: {p == q}");
Console.WriteLine($"Box p.Equals(q): {p.Equals(q)}");

string s = "hello";
string t = new string("hello".ToCharArray());
Console.WriteLine($"s == t: {s == t}");
Console.WriteLine($"ReferenceEquals(s, t): {ReferenceEquals(s, t)}");

double nan = double.NaN;
Console.WriteLine($"nan == nan: {nan == nan}");
Console.WriteLine($"nan.Equals(nan): {nan.Equals(nan)}");

record Point(int X, int Y);

class Box
{
    public int X { get; }
    public int Y { get; }
    public Box(int x, int y) { X = x; Y = y; }
}
Output
a == b: True
ReferenceEquals(a, b): False
ReferenceEquals(a, c): True
distinct points: 1
Box p == q: False
Box p.Equals(q): False
s == t: True
ReferenceEquals(s, t): False
nan == nan: False
nan.Equals(nan): True
  • Verdict: native. A record gets value equality from its fields for ==, Equals and GetHashCode. A plain class compares references with both == and Equals. ReferenceEquals always compares references.
  • string overloads == to compare characters, with an ordinal, case-sensitive comparison.
  • double.Equals treats NaN as equal to NaN. The == operator does not.

This code runs but gives a wrong answer on purpose.

object a = 42;
object b = 42;
Console.WriteLine(a == b);
Console.WriteLine(a.Equals(b));
Output
False
True

Each assignment boxes 42 into a new object. == on two object operands compares references, so it is false. Equals is a virtual call, and int overrides it to compare values. The compiler picks == by the static types, so the same values give a different answer when they are typed as object.

JavaScriptGitHub
const a = { x: 1, y: 2 };
const b = { x: 1, y: 2 };
const c = a;
console.log("a === b:", a === b);
console.log("a === c:", a === c);

const samePoint = (p, q) => p.x === q.x && p.y === q.y;
console.log("samePoint(a, b):", samePoint(a, b));
console.log("distinct objects:", new Set([a, b, c]).size);

const key = (p) => `${p.x},${p.y}`;
console.log("distinct keys:", new Set([a, b, c].map(key)).size);

console.log("NaN === NaN:", NaN === NaN);
console.log("Object.is(NaN, NaN):", Object.is(NaN, NaN));
console.log("[NaN].indexOf(NaN):", [NaN].indexOf(NaN));
console.log("[NaN].includes(NaN):", [NaN].includes(NaN));
console.log("0 === -0:", 0 === -0);
console.log("Object.is(0, -0):", Object.is(0, -0));
Output
a === b: false
a === c: true
samePoint(a, b): true
distinct objects: 2
distinct keys: 1
NaN === NaN: false
Object.is(NaN, NaN): true
[NaN].indexOf(NaN): -1
[NaN].includes(NaN): true
0 === -0: true
Object.is(0, -0): false
  • Verdict: idiom. === compares primitives by value and objects by identity. JavaScript has no hook that changes what === does for a class, so value equality of objects is a function that the program writes.
  • A Set and a Map compare keys with SameValueZero, which is identity for objects. A common idiom is a string key made from the fields.
  • There are four equality algorithms. == converts types. === does not. Object.is treats NaN as equal to itself and 0 as different from -0. SameValueZero, used by includes, Set and Map, treats NaN as equal to itself and 0 as equal to -0.

This code runs but gives a wrong answer on purpose.

console.log(0 == "");
console.log("0" == false);
console.log(null == undefined);
console.log(null == 0);
console.log([] == false);
console.log("1,2" == [1, 2]);
Output
true
true
true
false
true
true

== converts the operands before it compares them. A string becomes a number, a boolean becomes a number and an object becomes a primitive. So 0 == "" is true, and an empty array is equal to false. null is loosely equal to undefined and to nothing else. Use ===.

This code runs but gives a wrong answer on purpose.

const visits = new Map();
visits.set([1, 2], "first");
console.log(visits.get([1, 2]));
console.log(visits.size);
Output
undefined
1

Each array literal makes a new array, and the map compares keys by identity. The second [1, 2] is a different key, so get finds nothing. Use a string key such as "1,2", or keep the array object and use it again.

TypeScriptGitHub
type Point = { readonly x: number; readonly y: number };

function samePoint(p: Point, q: Point): boolean {
  return p.x === q.x && p.y === q.y;
}

const a: Point = { x: 1, y: 2 };
const b: Point = { x: 1, y: 2 };
const c = a;
console.log("a === b:", a === b);
console.log("a === c:", a === c);
console.log("samePoint(a, b):", samePoint(a, b));

const key = (p: Point): string => `${p.x},${p.y}`;
const seen = new Map<string, Point>();
for (const p of [a, b, c]) seen.set(key(p), p);
console.log("distinct keys:", seen.size);
Output
a === b: false
a === c: true
samePoint(a, b): true
distinct keys: 1
  • Verdict: idiom. The run time is JavaScript, so === compares objects by identity, and value equality is a function. The types make the function easier to write correctly.
  • The type checker reports a comparison of two types that have no value in common.

This code runs but gives a wrong answer on purpose.

const count: number = Number("3");
if (count === "3") {
  console.log("three");
} else {
  console.log("not three");
}
Output
not three

The type checker reports error TS2367: "This comparison appears to be unintentional because the types 'number' and 'string' have no overlap." A runner that only strips the types, such as Node, runs the program, and the comparison is always false. Compare values of one type: count === 3.

package main

import (
	"fmt"
	"math"
	"slices"
)

type Point struct{ X, Y int }

func main() {
	a := Point{1, 2}
	b := Point{1, 2}
	fmt.Println("a == b:", a == b)

	pa, pb, pc := &a, &b, &a
	fmt.Println("pa == pb:", pa == pb)
	fmt.Println("pa == pc:", pa == pc)

	counts := map[Point]int{}
	counts[a]++
	counts[b]++
	fmt.Println("distinct points:", len(counts), "count of a:", counts[a])

	xs := []int{1, 2}
	ys := []int{1, 2}
	fmt.Println("slices.Equal(xs, ys):", slices.Equal(xs, ys))

	var e1, e2 any = Point{1, 2}, Point{1, 2}
	fmt.Println("e1 == e2:", e1 == e2)

	nan := math.NaN()
	fmt.Println("nan == nan:", nan == nan)
}
Output
a == b: true
pa == pb: false
pa == pc: true
distinct points: 1 count of a: 2
slices.Equal(xs, ys): true
e1 == e2: true
nan == nan: false
  • Verdict: native. == compares structs field by field and arrays element by element. Pointers are equal when they point to the same variable. So == on a value is value equality, and == on pointers is identity.
  • A comparable struct can be a map key with no extra code.
  • Slices, maps and functions are not comparable, except with nil. slices.Equal and maps.Equal compare contents.
  • Two interface values are equal when their dynamic types are identical and their dynamic values are equal.

This code fails on purpose. The output below is the error.

package main

import "fmt"

func main() {
	var x, y any = []int{1}, []int{1}
	fmt.Println(x == y)
}

The program compiles, because interface values are comparable. At run time both dynamic types are []int, which is not comparable, so the comparison panics.

RustGitHub
use std::collections::HashSet;

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let a = Point { x: 1, y: 2 };
    let b = Point { x: 1, y: 2 };
    let c = &a;
    println!("a == b: {}", a == b);
    println!("ptr::eq(&a, &b): {}", std::ptr::eq(&a, &b));
    println!("ptr::eq(&a, c): {}", std::ptr::eq(&a, c));

    let set: HashSet<Point> = [a.clone(), b.clone(), c.clone()].into_iter().collect();
    println!("distinct points: {}", set.len());

    let s = String::from("hello");
    println!("s == \"hello\": {}", s == "hello");

    let nan = f64::NAN;
    println!("nan == nan: {}", nan == nan);
    println!("nan.total_cmp(&nan): {:?}", nan.total_cmp(&nan));
}
Output
a == b: true
ptr::eq(&a, &b): false
ptr::eq(&a, c): true
distinct points: 1
s == "hello": true
nan == nan: false
nan.total_cmp(&nan): Equal
  • Verdict: native. == calls PartialEq::eq, and #[derive(PartialEq)] compares the fields. std::ptr::eq compares addresses.
  • Eq marks a type whose equality is reflexive. f64 is PartialEq but not Eq, because NaN != NaN.
  • HashSet and HashMap need Eq + Hash for their keys. The derive keeps the two consistent.

This code does not compile, on purpose.

struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let a = Point { x: 1, y: 2 };
    let b = Point { x: 1, y: 2 };
    println!("{}", a == b);
    println!("{} {}", a.x, b.y);
}

rustc reports error E0369: binary operation == cannot be applied to type Point. A type has no == until it implements PartialEq. The fix is #[derive(PartialEq)].

This code does not compile, on purpose.

use std::collections::HashSet;

fn main() {
    let mut seen = HashSet::new();
    seen.insert(0.5_f64);
    println!("{}", seen.len());
}

f64 does not implement Eq or Hash, so insert is not available. Use integer keys, or wrap the value in a type that defines equality with total_cmp and hashes the bits.

CREATE TABLE users (name TEXT, email TEXT);
INSERT INTO users VALUES ('ann', 'ann@example.com'), ('bob', NULL), ('cy', NULL);

SELECT 'NULL = NULL is null', (NULL = NULL) IS NULL;
SELECT 'rows where email = NULL', count(*) FROM users WHERE email = NULL;
SELECT 'rows where email IS NULL', count(*) FROM users WHERE email IS NULL;
SELECT 'NULL IS NOT DISTINCT FROM NULL', NULL IS NOT DISTINCT FROM NULL;
SELECT 'distinct emails', count(*) FROM (SELECT DISTINCT email FROM users);
Output
NULL = NULL is null|1
rows where email = NULL|0
rows where email IS NULL|2
NULL IS NOT DISTINCT FROM NULL|1
distinct emails|2
  • Verdict: native. = compares values. When either side is NULL, the result is NULL, not true or false, so a WHERE clause with = NULL selects no rows.
  • IS and IS NOT DISTINCT FROM treat two NULL values as equal. IS is a short form that SQLite adds. Other databases need IS NOT DISTINCT FROM.
  • DISTINCT and GROUP BY treat two NULL values as the same, so the three rows have two distinct emails: one address and one NULL.
  • A row has no identity apart from its key. Equality of rows is equality of their columns.
BashGitHub
a="hello"
b="hel"
b+="lo"
if [[ $a == "$b" ]]; then
  echo "same text"
fi

pattern='h*'
if [[ $a == $pattern ]]; then
  echo "unquoted: matches as a pattern"
fi
if [[ $a == "$pattern" ]]; then
  echo "quoted: matches as text"
else
  echo "quoted: does not match as text"
fi

if [[ 1 -eq 01 ]]; then
  echo "1 -eq 01: equal as numbers"
fi
if [[ 1 != 01 ]]; then
  echo "1 != 01: different as text"
fi
Output
same text
unquoted: matches as a pattern
quoted: does not match as text
1 -eq 01: equal as numbers
1 != 01: different as text
  • Verdict: idiom. Shell values are strings. == inside [[ ]] matches the left side against a pattern on the right side. A quoted right side matches as plain text. -eq compares integers.
  • Bash has no objects, so it has no identity test.

This code runs but gives a wrong answer on purpose.

expected='*'
actual="anything"
if [[ $actual == $expected ]]; then
  echo "match"
else
  echo "no match"
fi
Output
match

The right side is not quoted, so * is a pattern that matches any string. Quote the right side: [[ $actual == "$expected" ]].

  • Structural and nominal equality. Some languages compare only values of the same class. A Python data class compares only with an instance of the identical type.5 Others compare any two values with the same shape.
  • Ordering and equality. A sorted set in C++ or Java uses an order, not equals. Two elements are the same when neither is less than the other. If the order and equals disagree, a sorted set and a hash set can hold different elements for the same input. The Java Double documentation notes that its compareTo is consistent with equals.14
  • Equality of functions. Two functions are equal if they give the same result for every input. A program cannot decide this in general, so languages compare functions by identity or not at all. Go does not allow == on functions.2
  • Equality of errors and enums. Sum types compare by their case and their fields. Error value are often compared with a sentinel value, which is an identity test.
  • Equality up to case, Unicode form or locale. Two strings with different bytes can be the same text for a reader. UTF-8 covers normalization.
  • Approximate equality. Floating point code often compares with a tolerance, abs(a - b) <= eps. This test is not transitive, so it cannot be the equality of a set.

Pitfalls

Identity where equality was meant

The most common mistake is == on references in a language where == means identity.

This code runs but gives a wrong answer on purpose.

public class Main {
    public static void main(String[] args) {
        String s = "hello";
        String t = new StringBuilder("hel").append("lo").toString();
        System.out.println(s == t);
        System.out.println(s.equals(t));
    }
}
Output
false
true

t is a new String with the same characters, so == is false. The JLS says that == on two String operands tests if they refer to the same object, and that equals compares the contents.22 String literals in one program are often the same object, so the bug can hide in tests that use only literals and appear with text from input. C has the same bug with == on two char arrays.

Boxed values

Boxing turns a primitive value into an object. Then == compares references.

This code runs but gives a wrong answer on purpose.

public class Main {
    public static void main(String[] args) {
        Integer small1 = Integer.valueOf(127);
        Integer small2 = Integer.valueOf(127);
        Integer large1 = Integer.valueOf(128);
        Integer large2 = Integer.valueOf(128);
        System.out.println(small1 == small2);
        System.out.println(large1 == large2);
        System.out.println(large1.equals(large2));
    }
}
Output
true
false
true

Integer.valueOf always caches the values from -128 to 127.24 The two 127 objects are one object, and the two 128 objects are two objects on this JVM. The language does not fix the result outside the cache range.23 So a test with small numbers passes and the program fails with larger ones. Compare boxed values with equals, or unbox them. C# has the same trap when two numbers are typed as object.

Equal values with different hash codes

This code runs but gives a wrong answer on purpose.

import java.util.HashSet;
import java.util.Set;

public class Main {
    static final class Point {
        final int x;
        final int y;

        Point(int x, int y) {
            this.x = x;
            this.y = y;
        }

        @Override
        public boolean equals(Object o) {
            return o instanceof Point p && p.x == x && p.y == y;
        }
    }

    public static void main(String[] args) {
        Set<Point> seen = new HashSet<>();
        seen.add(new Point(1, 2));
        seen.add(new Point(1, 2));
        System.out.println(new Point(1, 2).equals(new Point(1, 2)));
        System.out.println(seen.size());
        System.out.println(seen.contains(new Point(1, 2)));
    }
}
Output
true
2
false

The class overrides equals and not hashCode. As far as is reasonably practical, Object.hashCode returns distinct integers for distinct objects.9 So two equal points go to different buckets, and the set never compares them. The fix is a hashCode from the same fields, such as Objects.hash(x, y), or a record. Python stops this mistake at the first use:

This code raises TypeError, on purpose.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __eq__(self, other):
        return isinstance(other, Point) and (self.x, self.y) == (other.x, other.y)


seen = {Point(1, 2)}
print(len(seen))

The class defines __eq__ and no __hash__, so Python sets __hash__ to None, and the set raises TypeError: unhashable type.12

A key that changes

This code runs but gives a wrong answer on purpose.

import java.util.HashSet;
import java.util.Set;

public class Main {
    static final class Point {
        int x;
        int y;

        Point(int x, int y) {
            this.x = x;
            this.y = y;
        }

        @Override
        public boolean equals(Object o) {
            return o instanceof Point p && p.x == x && p.y == y;
        }

        @Override
        public int hashCode() {
            return 31 * x + y;
        }
    }

    public static void main(String[] args) {
        Set<Point> seen = new HashSet<>();
        Point p = new Point(1, 2);
        seen.add(p);
        p.x = 5;
        System.out.println(seen.contains(p));
        System.out.println(seen.size());
        for (Point q : seen) {
            System.out.println(q == p);
        }
    }
}
Output
false
1
true

The set holds the object p, but contains(p) is false. The set stored p in the bucket for the hash code of (1, 2), and now looks in the bucket for (5, 2). Do not change a field that equality uses while the object is a key. Use immutable keys.

Loose equality

This code runs but gives a wrong answer on purpose.

console.log(0 == "");
console.log("0" == false);
console.log(null == undefined);
console.log(null == 0);
console.log([] == false);
console.log("1,2" == [1, 2]);
Output
true
true
true
false
true
true

== converts its operands before the comparison, and the rules differ for each pair of types.13 An empty string, the string "0", false and an empty array are all loosely equal to 0 or to false. Use ===.

Objects as map keys in JavaScript

This code runs but gives a wrong answer on purpose.

const visits = new Map();
visits.set([1, 2], "first");
console.log(visits.get([1, 2]));
console.log(visits.size);
Output
undefined
1

A Map compares keys with SameValueZero, which is identity for objects.13 The second [1, 2] is a new array, so it is a different key. Use a string key, such as "1,2", or keep the key object.

NULL in SQL

This code runs but gives a wrong answer on purpose.

CREATE TABLE users (name TEXT, email TEXT);
INSERT INTO users VALUES ('ann', 'ann@example.com'), ('bob', NULL);

SELECT count(*) FROM users WHERE email = NULL;
SELECT count(*) FROM users WHERE email IS NULL;
Output
0
1

email = NULL is NULL for every row, so the WHERE clause keeps no row. The PostgreSQL documentation warns not to write expression = NULL, because NULL is not equal to NULL.29 Use IS NULL, or IS NOT DISTINCT FROM to compare two columns that can be NULL.

A comparison that fails at run time

This code fails on purpose. The output below is the error.

package main

import "fmt"

func main() {
	var x, y any = []int{1}, []int{1}
	fmt.Println(x == y)
}

Interface values are comparable, so the program compiles. Both dynamic types are []int, which is not comparable, so the comparison panics at run time.2 The same panic can come from a struct with an interface field or from a map key of interface type. Use reflect.DeepEqual or a comparison that knows the types.

A pattern in place of a string

This code runs but gives a wrong answer on purpose.

expected='*'
actual="anything"
if [[ $actual == $expected ]]; then
  echo "match"
else
  echo "no match"
fi
Output
match

In [[ ]], the right side of == is a pattern unless it is quoted.27 * matches any string. Quote the right side: [[ $actual == "$expected" ]].

Cost

An identity test compares two addresses. It takes constant time and does not touch the objects.

A value equality visits the parts of the values. For a string or a list, the time grows with the length of the shorter value, and the test stops at the first difference. For a tree of objects, it visits each node. A cycle in the objects makes a naive recursive equality loop forever. Python's built-in containers assume that identical objects are equal, so they skip the equality test for an element that is the same object.8

A hash table needs one hash computation and, on average, a small number of equality tests for each lookup. A slow hashCode or __hash__ makes every lookup slow. A hash function that gives many equal codes puts many keys in one bucket, and then each lookup does many equality tests.

Interning trades memory and a table lookup at creation time for constant-time equality later. It works best for values that are created once and compared many times, such as identifiers in a compiler.

History

McCarthy's 1960 paper on LISP defined two predicates. eq is defined only for atoms, and is true when the two atoms are the same symbol. equal is true when two symbolic expressions have the same structure, and McCarthy defines it by recursion over car and cdr with eq at the atoms.20 In later Lisps, EQ is the identity test for any object and EQUAL is the structural test.31

In 1993, Henry Baker argued that neither EQ nor EQUAL is wrong. EQ is correct for mutable objects and EQUAL is correct for immutable ones, and the mistake of Lisp was to not separate the two kinds of objects. He proposed one predicate, EGAL, for both.31 Languages with value types and records follow this idea: a mutable object compares by identity, and an immutable value compares by its contents.

Kotlin names the two tests with two operators: == for equality and === for identity.6 Java records, C# records and Python data classes write the equality and the hash from the fields, so the two stay consistent.345 Python 3.8 started to warn about is with a literal.21

References

  1. The Python Language Reference, Expressions, Python 3.14, 6.10.3 Identity comparisons
  2. The Go Programming Language Specification, Comparison operators
  3. Java SE 25 API, java.lang.Record, equals(Object)
  4. C# language reference, Equality operators, Value types equality, Record types equality, String equality
  5. dataclasses, Python 3.14, @dataclasses.dataclass, the eq and frozen parameters
  6. Kotlin documentation, Equality, Structural equality, Referential equality, Floating-point numbers equality
  7. Rust standard library, Trait PartialEq, description
  8. The Python Language Reference, Expressions, Python 3.14, 6.10.1 Value comparisons
  9. Java SE 25 API, java.lang.Object, equals(Object) and hashCode()
  10. C# programming guide, Equality comparisons, value equality and reference equality, Object.ReferenceEquals
  11. Rust standard library, Trait Eq, description
  12. The Python Language Reference, Data model, Python 3.14, 3.3.1 Basic customization, object.__hash__
  13. Equality comparisons and sameness, MDN, Loose equality, strict equality, same-value-zero equality, same-value equality
  14. Java SE 25 API, java.lang.Double, Floating-point Equality, Equivalence, and Comparison
  15. Double.Equals Method, .NET API reference, Remarks
  16. The Python Language Reference, Expressions, Python 3.14, 6.10.2 Membership test operations
  17. Working Draft, Programming Languages: C++, [class.eq] Equality operator
  18. N1570, Committee Draft of ISO/IEC 9899:2011 (C11), 6.5.9 Equality operators, paragraph 2
  19. N1570, Committee Draft of ISO/IEC 9899:2011 (C11), 6.2.6.1 General, paragraph 6
  20. J. McCarthy, Recursive functions of symbolic expressions and their computation by machine, Part I, Communications of the ACM 3(4), 184-195, 1960, section 3, the elementary functions eq and equal
  21. What's New In Python 3.8, Changes in Python behavior
  22. The Java Language Specification, Java SE 25 Edition, 15.21.3 Reference Equality Operators == and !=
  23. The Java Language Specification, Java SE 25 Edition, 5.1.7 Boxing Conversion
  24. Java SE 25 API, java.lang.Integer, valueOf(int)
  25. Rust standard library, Function std::ptr::eq, description
  26. about_Comparison_Operators, PowerShell documentation, Equality
  27. Bash Reference Manual, 3.2.5.2 Conditional Constructs, [[...]]
  28. SQLite, SQL Language Expressions, The IS and IS NOT operators
  29. PostgreSQL 18 Documentation, 9.2 Comparison Functions and Operators
  30. SQLite, The SELECT statement, Generation of the set of result rows, and Removal of duplicate rows
  31. H. G. Baker, Equal rights for functional objects or, the more things change, the more they are the same, ACM SIGPLAN OOPS Messenger 4(4), 2-27, 1993, section 2 and section 3

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/EYF876/text.yaml