Java hashCode and toString: Writing Them Correctly
How Java's hashCode and toString methods work and how to override them: the equals/hashCode contract, why HashSet breaks without it, Objects.hash and Arrays.hashCode, avoiding collisions, writing toString with getClass().getName(), printing arrays, and identity versions of both.
kvi5hnuCode Sprout team member10 min readOn this page
The previous article showed how to override equals. Two more Object methods almost always come along with it: hashCode, which hash-based collections rely on, and toString, which turns an object into readable text. This article shows how to write both correctly, and what goes wrong if you don't.
The hashCode Method
A hash code is an int computed from an object. A good hash function spreads values out, so that two different objects are unlikely to get the same number. The integer can be any int value, including negative ones.
Here are some hash codes produced by String.hashCode:
| String | Hash code |
|---|---|
"Java" | 2301506 |
"Coffee" | 2023803884 |
"Kettle" | -2050934669 |
String computes its hash code with a simple formula, "multiply by 31 and add":
int hash = 0;
for (int i = 0; i < length(); i++)
hash = 31 * hash + charAt(i);
(The result is cached in the string after the first computation, and integer overflow simply wraps around. That's why "Kettle" ends up negative.)
The default hash code
hashCode is defined in Object, so every object has a default hash code. It's an identity hash code: it's tied to the object itself, not its contents, and is typically derived from its memory address or a random number stored in the object header. Consider:
var s = "Go";
var sb = new StringBuilder(s);
var t = new String("Go");
var tb = new StringBuilder(t);
| Object | Hash code |
|---|---|
s | 2312 |
t | 2312 |
sb | some identity value, e.g. 20526976 |
tb | a different identity value, e.g. 20527144 |
s and t have the same hash code because String.hashCode is derived from the contents. sb and tb have different hash codes because StringBuilder doesn't override hashCode, so the identity-based Object.hashCode is used. (The exact numbers differ from run to run.)
The rule: equal objects must have equal hash codes
If you redefine equals, you must also redefine hashCode, at least for objects that might be stored in a hash table. Hash tables (HashMap, HashSet, covered in the collections part) use the hash code to pick a bucket, and only then call equals to compare objects within that bucket.
The contract:
- If
x.equals(y)istrue, thenx.hashCode()must equaly.hashCode(). - If the object doesn't change, repeated calls to
hashCodereturn the same value (during one run of the program). - Unequal objects may share a hash code (a collision), but fewer collisions mean faster hash tables.

Break rule 1, and hash collections silently fail:
class NoHash {
private final String id;
NoHash(String id) { this.id = id; }
@Override public boolean equals(Object o) { return o instanceof NoHash other && id.equals(other.id); }
// no hashCode: inherits the identity-based Object.hashCode
}
var set = new HashSet<NoHash>();
set.add(new NoHash("42"));
set.contains(new NoHash("42")); // false, although the objects are equal!
The two equal objects have different identity hash codes, so contains looks in the wrong bucket. Duplicates can end up in sets, and map lookups miss existing keys.
Your definitions of equals and hashCode must be compatible. If Employee.equals compares employee IDs, then hashCode must hash the IDs, not names or memory addresses. Never include fields in hashCode that equals ignores.
Writing hashCode
Combine the hash codes of the fields used in equals, so that the results are widely scattered. A first attempt for Employee:
public int hashCode() {
return 19 * name.hashCode()
+ 23 * Double.valueOf(salary).hashCode()
+ 29 * startDate.hashCode();
}
Two improvements:
- Use the null-safe
Objects.hashCode(x), which returns0fornullandx.hashCode()otherwise. - Use the static
Double.hashCode(value)(Java 8+) to avoid creating aDoubleobject. Every wrapper class (Integer,Long,Short,Byte,Double,Float,Character,Boolean) has such a statichashCodemethod.
public int hashCode() {
return 19 * Objects.hashCode(name)
+ 23 * Double.hashCode(salary)
+ 29 * Objects.hashCode(startDate);
}
Simplest of all, call Objects.hash with all fields. It combines their hash codes for you:
@Override
public int hashCode() {
return Objects.hash(name, salary, startDate);
}
Objects.hash is varargs, so it creates an array and boxes primitives on every call. That's fine for most classes. For hash codes computed millions of times, write the combination by hand: 31 * a + b style, as String does.
Arrays and hash codes
Be careful with array fields. An array's own hashCode is the identity hash from Object; it doesn't depend on the elements. Use the static Arrays.hashCode, which combines the element hash codes (with overloads for all primitive arrays and Object[]). For multidimensional arrays, use Arrays.deepHashCode.
Arrays.hashCode(Object[]) works almost like String.hashCode, with a twist: it starts at 1, so that an empty array (hash code 1) is distinguishable from null (hash code 0):
public static int hashCode(Object[] a) {
if (a == null) return 0;
int result = 1; // starting at 1, not 0
for (Object element : a)
result = 31 * result + (element == null ? 0 : element.hashCode());
return result;
}
Objects.hash calls Arrays.hashCode on its argument array. Consequently, Objects.hash(x) equals 31 + x.hashCode(). (So don't expect Objects.hash(x) to equal x.hashCode().)
Records
A record automatically provides a hashCode derived from the hash codes of its components, consistent with its generated equals. The exact algorithm is deliberately left unspecified by the Java Language Specification. (OpenJDK currently combines component hashes with "multiply by 31 and add", starting from zero.) Don't depend on specific values.
The toString Method
toString produces a text description of an object. Many JDK classes print themselves as the class name followed by their state in brackets; a record, for example:
Point[x=10, y=20]
That convention is easy to copy. A first version for Employee:
public String toString() {
return "Employee[name=" + name
+ ",salary=" + salary
+ ",startDate=" + startDate
+ "]";
}
You can do a little better. Instead of hardwiring the class name, call getClass().getName():
@Override
public String toString() {
return getClass().getName()
+ "[name=" + name
+ ",salary=" + salary
+ ",startDate=" + startDate
+ "]";
}
This works for subclasses too. A subclass programmer should still define toString and add the subclass's fields. If the superclass uses getClass().getName(), the subclass can simply call super.toString():
public class Manager extends Employee {
. . .
@Override
public String toString() {
return super.toString() + "[bonus=" + bonus + "]";
}
}
A Manager then prints as
Manager[name=Priya Nair,salary=91000.0,startDate=2016-04-11][bonus=6500.0]
(getClass().getName() returns the fully qualified name, such as com.example.Manager. getClass().getSimpleName() returns just Manager.)
Where toString is called automatically
You rarely call toString yourself. String concatenation with + calls it for you whenever one operand is an object:
var p = new Point(10, 20);
String label = "Cursor at " + p; // automatically invokes p.toString()
Likewise, System.out.println(x) calls x.toString() (via String.valueOf) and prints the result. String formatting with %s, string templates in loggers, and debuggers all use toString.
The default toString
Object.toString prints the class name, an @ sign and the hash code in hexadecimal:
System.out.println(System.out);
java.io.PrintStream@3e6fa38a
That's what you get when a class (here, PrintStream) doesn't override toString. Its output is useless for humans, which is why you should override it.
toString for logging
A good toString pays off most in logs and debugger views:
System.out.println("Order state: " + order);
Even better, use a logger (see the logging article in the exceptions part):
logger.log(Level.INFO, "Order state: " + order);
Getting the Original Behavior Back
In the unlikely case that you need the unmodified Object behavior after equals, hashCode or toString have been overridden:
| Instead of | Use |
|---|---|
equals | == |
hashCode | System.identityHashCode(obj) |
toString | Objects.toIdentityString(obj) (Java 19+) |
They return what Object's methods would have returned. IdentityHashMap uses identity comparison and identity hash codes throughout.
Everything Together
import java.time.LocalDate;
import java.util.*;
public class Solution {
public static void main(String[] args) {
for (String s : List.of("Java", "Coffee", "Kettle")) {
System.out.println(s + " " + s.hashCode());
}
var s = "Go";
var t = new String("Go");
System.out.println(s.hashCode() + " " + t.hashCode()); // same: content-based
// collisions with a weak date hash
Set<Integer> weak = new HashSet<>(), good = new HashSet<>();
int count = 0;
for (var d = LocalDate.of(2000, 1, 1); d.getYear() < 2030; d = d.plusDays(1)) {
weak.add(19 * d.getYear() + 23 * d.getMonthValue() + 29 * d.getDayOfMonth());
good.add(31 * 12 * d.getYear() + 31 * d.getMonthValue() + d.getDayOfMonth());
count++;
}
System.out.println(count + " dates: " + weak.size() + " weak hashes, " + good.size() + " good hashes");
System.out.println(Objects.hash("x") == 31 + "x".hashCode());
System.out.println(Arrays.hashCode(new int[0]) + " " + Arrays.hashCode((int[]) null));
// breaking hashCode breaks HashSet
var set = new HashSet<NoHash>();
set.add(new NoHash("42"));
System.out.println("contains equal object? " + set.contains(new NoHash("42")));
var set2 = new HashSet<WithHash>();
set2.add(new WithHash("42"));
System.out.println("contains equal object? " + set2.contains(new WithHash("42")));
// toString
var omar = new Employee("Omar Haddad", 52000, 2019, 9, 2);
var boss = new Manager("Priya Nair", 91000, 2016, 4, 11);
boss.setBonus(6500);
System.out.println(omar);
System.out.println("The boss is " + boss);
int[] scores = {88, 72, 95};
System.out.println(("" + scores).startsWith("[I@") + " " + Arrays.toString(scores));
System.out.println(Arrays.deepToString(new int[][] {{1, 2}, {3}}));
record Point(int x, int y) { }
System.out.println(new Point(10, 20));
}
}
class Employee {
private final String name;
private final double salary;
private final LocalDate startDate;
Employee(String name, double salary, int year, int month, int day) {
this.name = name;
this.salary = salary;
startDate = LocalDate.of(year, month, day);
}
@Override
public boolean equals(Object otherObject) {
if (this == otherObject) return true;
if (otherObject == null || getClass() != otherObject.getClass()) return false;
var other = (Employee) otherObject;
return Objects.equals(name, other.name) && Double.compare(salary, other.salary) == 0
&& Objects.equals(startDate, other.startDate);
}
@Override
public int hashCode() {
return Objects.hash(name, salary, startDate);
}
@Override
public String toString() {
return getClass().getName() + "[name=" + name + ",salary=" + salary + ",startDate=" + startDate + "]";
}
}
class Manager extends Employee {
private double bonus;
Manager(String name, double salary, int year, int month, int day) {
super(name, salary, year, month, day);
}
public void setBonus(double bonus) { this.bonus = bonus; }
@Override
public boolean equals(Object otherObject) {
if (!super.equals(otherObject)) return false;
var other = (Manager) otherObject;
return Double.compare(bonus, other.bonus) == 0;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), bonus);
}
@Override
public String toString() {
return super.toString() + "[bonus=" + bonus + "]";
}
}
@SuppressWarnings("overrides") // the missing hashCode is the point of this demo
class NoHash {
private final String id;
NoHash(String id) { this.id = id; }
@Override public boolean equals(Object o) { return o instanceof NoHash other && id.equals(other.id); }
// no hashCode: inherits the identity-based Object.hashCode
}
class WithHash {
private final String id;
WithHash(String id) { this.id = id; }
@Override public boolean equals(Object o) { return o instanceof WithHash other && id.equals(other.id); }
@Override public int hashCode() { return id.hashCode(); }
}
Java 2301506
Coffee 2023803884
Kettle -2050934669
2312 2312
10958 dates: 1516 weak hashes, 10958 good hashes
true
1 0
contains equal object? false
contains equal object? true
Employee[name=Omar Haddad,salary=52000.0,startDate=2019-09-02]
The boss is Manager[name=Priya Nair,salary=91000.0,startDate=2016-04-11][bonus=6500.0]
true [88, 72, 95]
[[1, 2], [3]]
Point[x=10, y=20]
Common questions
Can two unequal objects have the same hash code?
Yes. That's a collision, and it's always allowed, because there are far more possible objects than int values. Collisions only cost performance. Equal objects with different hash codes are the real bug.
Is the identity hash code the memory address?
Not on modern JVMs. HotSpot generates a pseudo-random number the first time hashCode is called and stores it in the object header, because objects move in memory during garbage collection. Two different objects can even get the same identity hash code.
Should hashCode use every field?
Use the same fields that equals compares, or a subset of them. Fewer fields still give a correct hash code, just with more collisions. Never use a field that equals ignores, because equal objects would then get different hash codes.
Why does my HashSet contain duplicates?
Usually because equals was overridden but hashCode wasn't. Another cause is equals(Employee) written instead of equals(Object), which overloads rather than overrides. A third cause is changing a field after adding the object. Use records or IDE-generated methods, and annotate the methods with @Override.
Is it OK to include all fields in toString?
Include the fields that help with debugging, but leave out secrets such as passwords, tokens and personal data, because toString output ends up in logs. For records with sensitive components, override toString to mask them.
Summary
hashCodereturns anint.Object's version is identity-based;Stringand other value classes compute it from their contents.- Equal objects must have equal hash codes. Override
hashCodewhenever you overrideequals, using exactly the same fields. OtherwiseHashSetandHashMapbreak. - Use
Objects.hash(fields...), or combineObjects.hashCode,Double.hashCodeand friends by hand. UseArrays.hashCode/deepHashCodefor array fields. Aim for few collisions. toStringshould print the class name and fields:getClass().getName() + "[field=...]". Subclasses append tosuper.toString().toStringis called implicitly by string concatenation andprintln. Print arrays withArrays.toStringorArrays.deepToString.- Records generate
equals,hashCodeandtoString.System.identityHashCodeandObjects.toIdentityStringgive the originalObjectbehavior.
Practice Questions
Class Isbn overrides equals (comparing the code string) but not hashCode. What happens with map.put(new Isbn("123"), book); map.get(new Isbn("123"))?
Most likely null. The two keys are equal, but their identity hash codes differ, so get searches the wrong bucket. Override hashCode to return code.hashCode().
Is it legal for two unequal objects to have the same hash code? Is it a problem?
It's legal (a collision); the contract only requires equal objects to have equal hash codes. Many collisions hurt performance, since hash tables degrade toward linear searches, but correctness is preserved.
Write hashCode for class Line { private final Point start, end; private final int[] dashPattern; } consistent with an equals that compares all three fields.
@Override
public int hashCode() {
return Objects.hash(start, end, Arrays.hashCode(dashPattern));
}
Arrays.hashCode is needed because an array's own hashCode ignores its contents.
What does System.out.println(new int[] {1, 2}) print, and how do you print the elements?
Something like [I@6d06d69c: the archaic type code [I plus an identity hash code. Use System.out.println(Arrays.toString(arr)) to get [1, 2].
Why use getClass().getName() in Employee.toString instead of the literal "Employee"?
So that subclasses get their correct class name automatically. A Manager prints as Manager[...], and Manager.toString can append its own fields to super.toString().
Previous: Java Object Class and the equals Method
Related reading
- Java Object Class and the equals Method
- Java final Classes and Methods, Casting, instanceof Patterns and protected Access
- Java Polymorphism and Dynamic Binding: How Method Calls Are Resolved
- Java Inheritance: Superclasses, Subclasses and Method Overriding
- Java Class Design Hints: Writing Clean, Maintainable Classes

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.