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 |
- 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
equalsandhashCodework in the same way. - The default string form names the type. Java's default
toStringreturns "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 - 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.
- Libraries call the methods. A
HashMapcallshashCodeto find a bucket andequalsto find the key in it,printcalls 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])
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);
}
}
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
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Idiom | |
| Java | Native | |
| C | Absent | C has no methods; libraries such as qsort and bsearch take a comparison function as a parameter. |
| C# | Native | |
| JavaScript | Absent | |
| TypeScript | Absent | As JavaScript; the types add no equality or hash hook, and === on objects is identity; no example file because it would repeat the JavaScript answer. |
| Go | Idiom | |
| Rust | Standard library | |
| Kotlin | Native | Any declares equals, hashCode and toString, and == calls equals; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Does not apply | SQL compares rows and values by value with its own rules; a table has no methods that a user overrides. |
| Bash | Does not apply | Bash has no objects; all values are strings. |
| PowerShell | Native | PowerShell objects are .NET objects, so they have Equals, GetHashCode and ToString from System.Object. |
| HTML | Does not apply | HTML is a markup language with no objects. |
| CSS | Does not apply | CSS is a style language with no objects. |
| Regular expressions | Does not apply | A 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,overrideoroverride fun. Kotlin'sAnyis "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__, andrepr()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
Stringmethod makes a type afmt.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
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)
True True
12.50 EUR Money(1250, 'EUR')
None
unhashable type: 'Money'
- Verdict: native. Every class inherits
__eq__,__ne__,__hash__,__repr__and__str__fromobject, and a class overrides the ones it needs. __ne__needs no code: by default it inverts the result of__eq__.printandstr()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';
}
true true
lunch 12.50 EUR
- Verdict: idiom. C++ has no root class. A type gets equality and ordering from operators:
= defaultonoperator==andoperator<=>compares the members in the order of their declaration. operator<<onstd::ostreamis the usual string form.std::unordered_mapneeds a specialization ofstd::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.
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);
}
}
true true false
lunch 12.50 EUR
- Verdict: native.
java.lang.Objectdeclaresequals,hashCodeandtoString, and every class inherits them. equalstakes anObject, so it must check the type first; theinstanceofpattern does the check and the cast in one step.a.equals(null)must returnfalse.Objects.hashbuilds a hash code from the same fields thatequalscompares, so aHashMapfinds 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);
}
True True False
lunch 12.50 EUR
Plain
- Verdict: native.
System.ObjectdeclaresEquals,GetHashCodeandToString, and every type inherits them. IEquatable<Money>adds anEqualswithout a cast, and the override ofEquals(object)calls it. The==operator does not callEqualsby itself, so the class defines==and!=too.HashCode.Combinemixes the fields thatEqualscompares. The defaultToStringreturns the name of the type, asPlainshows.
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({}));
false true
2 1
12.50 EUR [object Object]
- Verdict: absent.
Object.prototypegivestoStringandvalueOf, but no method for equality or hashing.===compares two objects by identity, and code cannot change that. - An
equalsmethod is only a convention:Set,Mapand===do not call it. To use value equality in aSetor as aMapkey, convert each object to a primitive key, askey()does. - A template literal and
String()calltoString. 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})
}
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 likeMoneycan be a map key with no code. - The
fmtpackage calls theStringmethod of a value that implementsfmt.Stringer. Without one,%vprints the fields in braces and%+vadds 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 anEqualmethod, and use a comparable key in maps.
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(", "));
}
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:
PartialEqandEqfor==,Hashfor hash maps,PartialOrdandOrdfor<and sorting,Debugfor{:?},Displayfor{}, andClonefor copies. #[derive]writes the code for most of them from the fields.Displaycannot be derived, so the type implements it by hand, andto_stringthen comes fromDisplay.- The derived
Ordcompares the fields in the order of their declaration, socurrencycomes first here.
Variations and related ideas
- Generated methods. Records in Java and C#, data classes in Kotlin,
@dataclassin 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 hasDisplayandDebug: one form is for users, the other for developers. Java and C# have onetoString; see string representation of an object. - Ordering. Ordering is not on
Objectin Java or C#; a type opts in withComparableorIComparable<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:
isin Python,==on references in Java,ReferenceEqualsin C#,===in JavaScript. See value equality and identity. - Methods for the run-time. Java's
Objectalso hasgetClass,waitandnotify, and C# hasGetType. They are universal, but a type does not override them.
Pitfalls
- Equality without a hash. A Java class that overrides
equalsand nothashCodebreaksHashMapandHashSet: 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 aHashMapstill callsObject.equals. Use@Override, and takeObject. - Equality across a class hierarchy. If
ColorPointextendsPointand adds a color toequals,point.equals(colorPoint)andcolorPoint.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 defineoperator ==to make it callEquals. 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
- Object (Java SE 21 & JDK 21), API documentation, Class Object; equals; hashCode; toString
- Data model, The Python Language Reference, 3.3.1 Basic customization
- Object.Equals Method, .NET API reference, Remarks
- Object.ToString Method, .NET API reference, Remarks
- Object.GetHashCode Method, .NET API reference, Remarks
- Any, Kotlin standard library API, Any
- Appendix C, Derivable Traits, The Rust Programming Language, whole appendix
- The Go Programming Language Specification, Comparison operators
- fmt package, Go standard library, type Stringer
- Equality comparisons and sameness, MDN, Introduction
- Object.prototype.toString(), JavaScript reference, MDN, Description
- Default comparisons, cppreference.com, Introduction
- Java version history, Wikipedia, Release table
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag N257JN Edit this page History Report an error Markdown