Programming Search⌘K

Conceptcore

Universal object methods

Also called standard object methods, object protocol, equals hashCode toString, java.lang.Object methods, System.Object methods, dunder methods, magic methods, special methods, derivable traits, Any methods.

Universal object methods are the small set of methods, such as equality, hash code and string form, that a language gives every object and that its libraries call, with defaults that a type overrides.

Applies to
core-languages

Idea

A program compares objects, puts them in hash tables, sorts them and prints them. The code of a hash map or of print does not know the types that it will get, so the language agrees on a few method names that every object has. The library calls these methods, and each type decides what they mean.

In Java the agreement is the class Object: "Class Object is the root of the class hierarchy. Every class has Object as a superclass."1 Its methods include equals, hashCode and toString. Python gives every class __eq__, __hash__, __repr__ and __str__ from object,2 C# gives Equals, GetHashCode and ToString from System.Object, and Kotlin gives equals, hashCode and toString from Any. Rust and Go have no root class, but they have the same roles as traits and interfaces that a type implements.

The default versions use the identity of the object: two objects are equal only if they are the same object, and the string form shows the type and an address or a hash. A type that holds a value, such as a point, an amount of money or a date, overrides them so that two objects with the same fields are equal, hash the same and print their fields.

How it works

The usual roles are:

Role Java Python C# Rust Go
equality equals __eq__ Equals, == PartialEq, Eq == (built in)
hash code hashCode __hash__ GetHashCode Hash none; map keys use ==
string form toString __str__, __repr__ ToString Display, Debug String() (fmt.Stringer)
ordering Comparable.compareTo __lt__ and the others IComparable<T>.CompareTo PartialOrd, Ord cmp.Compare, or a function
copy clone copy.copy MemberwiseClone Clone assignment copies a struct
  1. The default equality is identity. Python says that with the default methods "all objects compare unequal (except with themselves)".2 In C#, for a reference type, "the Equals(Object) method tests for reference equality".3 Java's default equals and hashCode work in the same way.
  2. The default string form names the type. Java's default toString returns "the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object."1 C#: "Default implementations of the Object.ToString method return the fully qualified name of the object's type."4
  3. A type overrides the methods together. Equality and the hash code are one contract: "If two objects are equal according to the equals method, then calling the hashCode method on each of the two objects must produce the same integer result."1 C# has the same rule,5 and Python says that "The only required property is that objects which compare equal have the same hash value".2 See the equality and hashing contract.
  4. Libraries call the methods. A HashMap calls hashCode to find a bucket and equals to find the key in it, print calls the string form, and a sort calls the ordering. A type that does not override them works, but with identity semantics.

The Python version of a point shows the difference. Plain keeps the defaults of object, and Point overrides equality, the hash and the string form:

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


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

    def __eq__(self, other):
        if not isinstance(other, Point):
            return NotImplemented
        return (self.x, self.y) == (other.x, other.y)

    def __hash__(self):
        return hash((self.x, self.y))

    def __repr__(self):
        return f"Point({self.x}, {self.y})"


a, b = Plain(1, 2), Plain(1, 2)
print(a == b, a == a, repr(a).startswith("<__main__.Plain object at"))

p, q = Point(1, 2), Point(1, 2)
print(p == q, p is q, len({p, q}))
print(p, [p])
Output
False True True
True False 1
Point(1, 2) [Point(1, 2)]

p and q are two objects (p is q is false), but they are equal, and the set keeps only one of them. print uses __repr__ because the class has no __str__.

In Java, a record gets the three methods from its fields, while a plain class keeps the methods of Object:

import java.util.HashSet;
import java.util.List;

public class Main {
    static final class Plain {
        final int x, y;

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

    record Point(int x, int y) {}

    public static void main(String[] args) {
        Plain a = new Plain(1, 2), b = new Plain(1, 2);
        System.out.println(a.equals(b) + " " + a.toString().startsWith("Main$Plain@"));

        Point p = new Point(1, 2), q = new Point(1, 2);
        System.out.println(p.equals(q) + " " + (p == q) + " " + new HashSet<>(List.of(p)).contains(q));
        System.out.println(p);
    }
}
Output
false true
true false true
Point[x=1, y=2]

In Java, == on two objects is always identity, so p == q is false even for the record. Value equality needs equals.

In languages

LanguageVerdictNote
PythonNative
C++Idiom
JavaNative
CAbsentC has no methods; libraries such as qsort and bsearch take a comparison function as a parameter.
C#Native
JavaScriptAbsent
TypeScriptAbsentAs JavaScript; the types add no equality or hash hook, and === on objects is identity; no example file because it would repeat the JavaScript answer.
GoIdiom
RustStandard library
KotlinNativeAny declares equals, hashCode and toString, and == calls equals; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLDoes not applySQL compares rows and values by value with its own rules; a table has no methods that a user overrides.
BashDoes not applyBash has no objects; all values are strings.
PowerShellNativePowerShell objects are .NET objects, so they have Equals, GetHashCode and ToString from System.Object.
HTMLDoes not applyHTML is a markup language with no objects.
CSSDoes not applyCSS is a style language with no objects.
Regular expressionsDoes not applyA regular expression language has no objects.
Language Verdict Mechanism
Python native object gives __eq__, __ne__, __hash__, __repr__, __str__ and __format__; the ordering methods return NotImplemented
JavaScript absent Object.prototype gives toString and valueOf; === on objects is identity, and no hook changes it
TypeScript absent as JavaScript
Java native java.lang.Object: equals, hashCode, toString, clone, getClass
Kotlin native Any: equals, hashCode, toString; == calls equals
C# native System.Object: Equals, GetHashCode, ToString, MemberwiseClone, GetType
Go idiom no root type; == compares comparable structs field by field; fmt.Stringer for the string form
Rust stdlib traits PartialEq, Eq, Hash, PartialOrd, Ord, Debug, Display, Clone, most of them derivable
C absent no methods; a library takes function pointers, such as the comparison function of qsort
C++ idiom no root class; operator== and operator<=>, which a class can default, operator<< on streams, a std::hash specialization
Bash n/a no objects
PowerShell native objects are .NET objects, with the members of System.Object
SQL n/a rows and values compare by value; there are no user methods on rows
Regex n/a no objects
HTML n/a no objects
CSS n/a no objects
  • Java, C# and Kotlin put the methods on the root class, so every object has them, and a class overrides them with @Override, override or override fun. Kotlin's Any is "The root of the Kotlin class hierarchy."6
  • Python calls the methods through operators and built-in functions: x==y calls x.__eq__(y), hash() calls __hash__, and repr() calls __repr__, which computes "the “official” string representation of an object".2
  • Rust uses one trait for each role. The derive attribute writes most of them from the fields, but not Display: "An example of a trait that can’t be derived is Display, which handles formatting for end users."7
  • Go has no hook for equality or hashing. The spec says: "Struct types are comparable if all their field types are comparable."8 For the string form, a String method makes a type a fmt.Stringer, and "The String method is used to print values passed as an operand to any format that accepts a string or to an unformatted printer such as Print."9
  • JavaScript compares objects by identity, and MDN notes that "JavaScript does not provide a general deep comparison operator".10 The string form is toString: "JavaScript automatically invokes it when encountering an object where a primitive value is expected."11
  • C++ has no root class, but "Comparison operator functions can be explicitly defaulted to request the compiler to generate the corresponding default comparison for a class."12
PythonGitHub
class Money:
    def __init__(self, cents, currency):
        self.cents, self.currency = cents, currency

    def __eq__(self, other):
        if not isinstance(other, Money):
            return NotImplemented
        return (self.cents, self.currency) == (other.cents, other.currency)

    def __repr__(self):
        return f"Money({self.cents!r}, {self.currency!r})"

    def __str__(self):
        return f"{self.cents / 100:.2f} {self.currency}"


m = Money(1250, "EUR")
print(m == Money(1250, "EUR"), m != Money(99, "EUR"))
print(str(m), repr(m))
print(Money.__hash__)
try:
    {m}
except TypeError as e:
    print(e)
Output
True True
12.50 EUR Money(1250, 'EUR')
None
unhashable type: 'Money'
  • Verdict: native. Every class inherits __eq__, __ne__, __hash__, __repr__ and __str__ from object, and a class overrides the ones it needs.
  • __ne__ needs no code: by default it inverts the result of __eq__. print and str() call __str__, and the interactive prompt and the debugger call __repr__.
  • A class that defines __eq__ and not __hash__ gets __hash__ = None, so its objects cannot go in a set or be dict keys. Add __hash__ only if the fields that __eq__ uses do not change.
#include <compare>
#include <cstdint>
#include <functional>
#include <iomanip>
#include <iostream>
#include <string>
#include <unordered_map>

struct Money {
    std::string currency;
    std::int64_t cents;

    bool operator==(const Money&) const = default;
    auto operator<=>(const Money&) const = default;
};

std::ostream& operator<<(std::ostream& out, const Money& m) {
    return out << m.cents / 100 << '.' << std::setw(2) << std::setfill('0') << m.cents % 100 << ' ' << m.currency;
}

template <>
struct std::hash<Money> {
    std::size_t operator()(const Money& m) const noexcept {
        std::size_t h = std::hash<std::string>{}(m.currency);
        return h ^ (std::hash<std::int64_t>{}(m.cents) + 0x9e3779b9 + (h << 6) + (h >> 2));
    }
};

int main() {
    Money a{"EUR", 1250}, b{"EUR", 1250};
    std::cout << std::boolalpha << (a == b) << ' ' << (a < Money{"USD", 5}) << '\n';
    std::unordered_map<Money, std::string> names{{a, "lunch"}};
    std::cout << names.at(b) << ' ' << a << '\n';
}
Output
true true
lunch 12.50 EUR
  • Verdict: idiom. C++ has no root class. A type gets equality and ordering from operators: = default on operator== and operator<=> compares the members in the order of their declaration.
  • operator<< on std::ostream is the usual string form. std::unordered_map needs a specialization of std::hash, which the code must write by hand; it must give equal hashes for equal objects.
  • The compiler also writes the copy constructor and the copy assignment, which copy each member.
JavaGitHub
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class Main {
    static final class Money {
        private final long cents;
        private final String currency;

        Money(long cents, String currency) {
            this.cents = cents;
            this.currency = Objects.requireNonNull(currency);
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof Money m)) return false;
            return cents == m.cents && currency.equals(m.currency);
        }

        @Override
        public int hashCode() {
            return Objects.hash(cents, currency);
        }

        @Override
        public String toString() {
            return String.format("%d.%02d %s", cents / 100, cents % 100, currency);
        }
    }

    public static void main(String[] args) {
        Money a = new Money(1250, "EUR"), b = new Money(1250, "EUR");
        System.out.println(a.equals(b) + " " + (a.hashCode() == b.hashCode()) + " " + a.equals(null));
        Map<Money, String> names = new HashMap<>();
        names.put(a, "lunch");
        System.out.println(names.get(b) + " " + a);
    }
}
Output
true true false
lunch 12.50 EUR
  • Verdict: native. java.lang.Object declares equals, hashCode and toString, and every class inherits them.
  • equals takes an Object, so it must check the type first; the instanceof pattern does the check and the cast in one step. a.equals(null) must return false.
  • Objects.hash builds a hash code from the same fields that equals compares, so a HashMap finds the value with a second object that is equal to the key.
using System;
using System.Collections.Generic;

var a = new Money(1250, "EUR");
var b = new Money(1250, "EUR");
Console.WriteLine($"{a.Equals(b)} {a == b} {ReferenceEquals(a, b)}");
var names = new Dictionary<Money, string> { [a] = "lunch" };
Console.WriteLine($"{names[b]} {a}");
Console.WriteLine(new Plain());

sealed class Plain { }

sealed class Money : IEquatable<Money>
{
    public long Cents { get; }
    public string Currency { get; }

    public Money(long cents, string currency)
    {
        Cents = cents;
        Currency = currency;
    }

    public bool Equals(Money? other) => other is not null && Cents == other.Cents && Currency == other.Currency;

    public override bool Equals(object? obj) => Equals(obj as Money);

    public override int GetHashCode() => HashCode.Combine(Cents, Currency);

    public override string ToString() => $"{Cents / 100}.{Cents % 100:D2} {Currency}";

    public static bool operator ==(Money? left, Money? right) => left is null ? right is null : left.Equals(right);

    public static bool operator !=(Money? left, Money? right) => !(left == right);
}
Output
True True False
lunch 12.50 EUR
Plain
  • Verdict: native. System.Object declares Equals, GetHashCode and ToString, and every type inherits them.
  • IEquatable<Money> adds an Equals without a cast, and the override of Equals(object) calls it. The == operator does not call Equals by itself, so the class defines == and != too.
  • HashCode.Combine mixes the fields that Equals compares. The default ToString returns the name of the type, as Plain shows.
JavaScriptGitHub
class Money {
  constructor(cents, currency) {
    this.cents = cents;
    this.currency = currency;
  }

  equals(other) {
    return other instanceof Money && this.cents === other.cents && this.currency === other.currency;
  }

  key() {
    return `${this.currency}:${this.cents}`; // a primitive that a Set or Map can compare
  }

  toString() {
    return `${(this.cents / 100).toFixed(2)} ${this.currency}`;
  }
}

const a = new Money(1250, "EUR");
const b = new Money(1250, "EUR");
console.log(a === b, a.equals(b));
console.log(new Set([a, b]).size, new Set([a, b].map((m) => m.key())).size);
console.log(`${a}`, String({}));
Output
false true
2 1
12.50 EUR [object Object]
  • Verdict: absent. Object.prototype gives toString and valueOf, but no method for equality or hashing. === compares two objects by identity, and code cannot change that.
  • An equals method is only a convention: Set, Map and === do not call it. To use value equality in a Set or as a Map key, convert each object to a primitive key, as key() does.
  • A template literal and String() call toString. Without an override, the result is [object Object].
package main

import "fmt"

type Money struct {
	Cents    int64
	Currency string
}

// String makes Money a fmt.Stringer.
func (m Money) String() string {
	return fmt.Sprintf("%d.%02d %s", m.Cents/100, m.Cents%100, m.Currency)
}

type Plain struct{ X, Y int }

func main() {
	a, b := Money{1250, "EUR"}, Money{1250, "EUR"}
	fmt.Println(a == b)
	names := map[Money]string{a: "lunch"}
	fmt.Println(names[b], a)
	fmt.Printf("%v %+v\n", Plain{1, 2}, Plain{1, 2})
}
Output
true
lunch 12.50 EUR
{1 2} {X:1 Y:2}
  • Verdict: idiom. Go has no root type. == works on any struct whose fields are all comparable, and it compares the fields, so a struct like Money can be a map key with no code.
  • The fmt package calls the String method of a value that implements fmt.Stringer. Without one, %v prints the fields in braces and %+v adds their names.
  • Code cannot change == or the hash of a map key. A type with a slice or map field is not comparable; give it an Equal method, and use a comparable key in maps.
RustGitHub
use std::collections::HashMap;
use std::fmt;

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
struct Money {
    currency: String,
    cents: i64,
}

impl fmt::Display for Money {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}.{:02} {}", self.cents / 100, self.cents % 100, self.currency)
    }
}

fn main() {
    let a = Money { currency: "EUR".to_string(), cents: 1250 };
    let b = a.clone();
    println!("{}", a == b);
    let mut names = HashMap::new();
    names.insert(a.clone(), "lunch");
    println!("{} {}", names[&b], a);
    println!("{:?}", a);
    let mut list = vec![Money { currency: "USD".to_string(), cents: 5 }, a];
    list.sort();
    let shown: Vec<String> = list.iter().map(|m| m.to_string()).collect();
    println!("{}", shown.join(", "));
}
Output
true
lunch 12.50 EUR
Money { currency: "EUR", cents: 1250 }
12.50 EUR, 0.05 USD
  • Verdict: stdlib. Each standard method is a trait in the standard library: PartialEq and Eq for ==, Hash for hash maps, PartialOrd and Ord for < and sorting, Debug for {:?}, Display for {}, and Clone for copies.
  • #[derive] writes the code for most of them from the fields. Display cannot be derived, so the type implements it by hand, and to_string then comes from Display.
  • The derived Ord compares the fields in the order of their declaration, so currency comes first here.
  • Generated methods. Records in Java and C#, data classes in Kotlin, @dataclass in Python and #[derive] in Rust write equality, hashing and the string form from the fields. Most value types should use them and not code by hand.
  • Display form and debug form. Python has __str__ and __repr__, and Rust has Display and Debug: one form is for users, the other for developers. Java and C# have one toString; see string representation of an object.
  • Ordering. Ordering is not on Object in Java or C#; a type opts in with Comparable or IComparable<T>. Most types have equality, but only some have a natural order. See natural ordering and comparator.
  • Identity equality. Each language also keeps an identity test: is in Python, == on references in Java, ReferenceEquals in C#, === in JavaScript. See value equality and identity.
  • Methods for the run-time. Java's Object also has getClass, wait and notify, and C# has GetType. They are universal, but a type does not override them.

Pitfalls

  • Equality without a hash. A Java class that overrides equals and not hashCode breaks HashMap and HashSet: two equal keys go to different buckets. Python protects the programmer here: "A class that overrides eq() and does not define hash() will have its hash() implicitly set to None."2 The objects then cannot go in a set.
  • A hash of mutable fields. If a field that the hash uses changes after the object goes into a hash set, the set looks in the wrong bucket and cannot find the object. Python says that for mutable objects a class "should not implement hash()".2
  • The wrong parameter type. In Java, public boolean equals(Point other) is an overload, not an override, so a HashMap still calls Object.equals. Use @Override, and take Object.
  • Equality across a class hierarchy. If ColorPoint extends Point and adds a color to equals, point.equals(colorPoint) and colorPoint.equals(point) can give different results, which breaks the rule that equality is symmetric. See the equality and hashing contract.
  • Logic that reads the string form. Java says of toString: "The string output is not necessarily stable over time or across JVM invocations."1 Do not parse it, and do not use it as a key.
  • == that does not call the method. In Java and JavaScript, == and === on objects compare identity, and in C# a class must define operator == to make it call Equals. Kotlin's == and Python's == call the equality method.

Cost

The default methods are cheap: identity equality compares two references, and the default hash comes from the identity of the object, so it does not read the fields. Value equality compares each field, so its cost grows with the size of the fields; for a list field it compares every element. A hash of a large object is also computed from all the fields that equality uses. A hash map calls the hash once for each lookup and calls equality only for the keys in the same bucket, so a good hash keeps the number of equality calls small.

History

Java made the methods part of the root class from its first version. JDK 1.0 was released on January 23, 1996,13 and Object is marked "Since: 1.0", with equals, hashCode and toString.1 Python 2.1 added the rich comparison methods __lt__, __eq__ and the others; PEP 207, by Guido van Rossum and David Ascher, proposed to "Allow separately overloading of <, >, <=, >=, ==, !=, both in classes and in C extensions."14 Later languages generate the methods: Rust derives them from the fields, and C++20 added defaulted comparison operators.12

References

  1. Object (Java SE 21 & JDK 21), API documentation, Class Object; equals; hashCode; toString
  2. Data model, The Python Language Reference, 3.3.1 Basic customization
  3. Object.Equals Method, .NET API reference, Remarks
  4. Object.ToString Method, .NET API reference, Remarks
  5. Object.GetHashCode Method, .NET API reference, Remarks
  6. Any, Kotlin standard library API, Any
  7. Appendix C, Derivable Traits, The Rust Programming Language, whole appendix
  8. The Go Programming Language Specification, Comparison operators
  9. fmt package, Go standard library, type Stringer
  10. Equality comparisons and sameness, MDN, Introduction
  11. Object.prototype.toString(), JavaScript reference, MDN, Description
  12. Default comparisons, cppreference.com, Introduction
  13. Java version history, Wikipedia, Release table
  14. PEP 207, Rich Comparisons, Header; Abstract

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/N257JN/text.yaml