Lesson · The Object Class & Core Contracts
java.util.Objects: the small toolbox behind clean contracts
14 min readjava.util.Objects
Null-safe comparison, hashes from fields, display with defaults, fail-fast checks and index guards: five helpers that turn the equals/hashCode/toString recipes into one-liners.
The null checks that pile up
The contract recipes keep needing the same three-line patterns, and the JDK ships them pre-written:
// hand-rolled, in equals: return a == null ? b == null : a.equals(b); // the same question, null-safe: return Objects.equals(a, b);
Predict: what does Objects.equals(null, null) return, and what about Objects.equals(null, "a")? True, then false, with no exception ever; the utility asks 'equal or both absent?' so the caller never writes the guard.
The toolbox
Six methods cover almost everything the contracts chapter keeps asking for:
| Method | Job | Detail worth knowing |
|---|---|---|
Objects.equals(a, b) | Null-safe equality | Two nulls are equal; one null is not; otherwise delegates to a.equals(b) |
Objects.hash(fields...) | A hash from several fields | Exactly the fields equals uses; varargs convenience, slight boxing cost |
Objects.hashCode(x) | A hash from one field | Convenient when the field can be null: null hashes to 0 |
Objects.toString(x, fallback) | Display with a default | Ideal for logs: never prints null when a phrase exists |
Objects.requireNonNull(x, msg) | Reject null at the boundary | Throws immediately with your message; the constructor's fail-fast guard |
Objects.checkIndex(i, length) | Bounds check for indexes | Throws IndexOutOfBoundsException with the numbers in the message |
These are the same three recipes from the contracts lessons, factory-made. Nothing here changes semantics; it removes the room for a forgotten guard line, which is where contract bugs live.
Fail fast, fail clearly: requireNonNull
The most valuable member is requireNonNull, used at construction boundaries:
User(String name, int level) { this.name = Objects.requireNonNull(name, "name must not be null"); this.level = level; }
- The object can never exist in a half-valid state: null is refused before any field is assigned.
- The message names the rule, and the stack trace points at the caller who broke it, not at some deep method three calls later.
- The supplier form
requireNonNull(name, () -> "user " + id + " needs a name")builds the message only when the failure happens; production code often uses it for expensive details. requireNonNullElse(value, fallback)covers the softer case: substitute a default instead of refusing.
A NaN-style mistake goes to the boundary, not into storage. Rejecting null in the constructor means every method afterwards may assume it away; that single guard deletes dozens of future checks.
Toolbox tester · the pattern, then the helper
pick a methodHand-rolled
With Objects
Objects.equals(null, null) → true, (null, "a") → false: no exception, ever.
The forgotten guard line is the classic equals bug; the utility cannot forget it.
Every result above was executed with javac and java; the messages are the tools' own output.
The index guards for vessel classes
Writing any collection-like class (the skeletal-implementations pattern from the interfaces chapter) means writing bounds checks; the utility makes them one line with the exact message callers expect:
Objects.checkIndex(index, length)in aget:IndexOutOfBoundsException: Index 5 out of bounds for length 3when the caller is wrong.Objects.checkFromIndexSize(from, size, length)for slices and ranges:range [2, 5) out of bounds for length 3and similar.- The exceptions are the standard ones collections already throw, so callers'
catchblocks and tests keep matching. - Fail-fast here is a kindness: the wrong index surfaces at the call that caused it, with the numbers attached, instead of corrupting state and failing later.
Use the toolbox where it earns its keep. A lone null check is fine written directly; guards that encode the same rule repeatedly (equals, hashCode, toString, constructors, container methods) are where Objects pays for itself.
The Objects playbook
Wiring the toolbox into a type, in order:
- Constructor:
requireNonNullevery reference parameter the object cannot live without, with the parameter's name in the message. - equals:
Objects.equalsfor reference fields;Objects.hash(or the single-field variant) for the matching hashCode. - toString:
Objects.toString(field, fallback)for nullable display fields. - Container classes:
checkIndex/checkFromIndexSizein getters and range operations. - Resist decoration: where a single plain null check reads better, keep it; the toolbox replaces patterns, not every line.
Small methods, large consequences. Five one-line helpers hold up the equals, hashCode, toString and fail-fast habits of the rest of this chapter; use them where the pattern repeats and the code stays honest.
The contracts chapter's plumbing, factory-made
Objects.equals makes comparisons null-safe, Objects.hash and hashCode build the field hashes equals demands, toString with a fallback cleans logs, requireNonNull (with an optional supplier) pushes invalid parameters out at the boundary, and the checkIndex family turns bounds checks into standard exceptions with standard messages.
Interview angles
Why use Objects.equals instead of a.equals(b)?+
Null safety and readability: two nulls are equal, one null never throws, and the call site reads as the question 'are these equal?' without a guard around it.
Inside equals implementations it removes the classic forgotten-null bug from every reference field comparison. Comparisons where both sides are known non-null can stay plain equals; the utility shines exactly where null is possible.
Objects.equals(a, b); // null-safe, symmetric in intent a.equals(b); // NPE when a is null
Common misconception: That it is merely shorter. It answers null cases with defined results; a.equals(b) answers them with a NullPointerException.
Follow-up: What does Objects.equals(null, null) return?
When do you reach for Objects.hash?+
In hashCode, with exactly the fields equals compares; Objects.hashCode(x) covers the single-field case and maps null to 0.
The convenience has a small cost (array creation and boxing), irrelevant outside the hottest paths. The correctness rule dwarfs it: the field list must match equals, and the fields must stay stable while stored, as the hashCode lesson proved.
@Override public int hashCode() { return Objects.hash(x, y); }
Common misconception: That Objects.hash replaces the contract. It implements a formula; matching the equals field list is still your job.
Follow-up: What does Objects.hashCode(null) return?
What does requireNonNull add over an if-check?+
One expression that rejects null, throws NullPointerException with your message, and reads as an assignment: the fail-fast constructor guard with zero ceremony.
The supplier overload builds the message lazily, for cases where the message is expensive. The discipline matters more than the method: null should die at the boundary, so every method after it may assume a valid object.
this.name = Objects.requireNonNull(name, "name must not be null"); this.name = Objects.requireNonNull(name, () -> "user " + id + " needs a name"); // lazy
Common misconception: That fail-fast is hostile. It is the opposite: the error points at the caller and the rule, at the first bad moment, instead of surfacing as corruption later.
Follow-up: Where should requireNonNull never appear?
Where do Objects.toString and requireNonNullElse fit?+
Both are about graceful defaults: toString(value, fallback) for display, and requireNonNullElse(value, fallback) for substitution when null is acceptable.
toString with a default keeps logs free of bare null without extra conditionals; requireNonNullElse chooses a default object instead of rejecting input, appropriate for optional settings and other soft parameters.
log("user " + Objects.toString(user, "anonymous")); String host = Objects.requireNonNullElse(config.host(), "localhost");
Common misconception: That both should be applied everywhere. Silence is not always a virtue: where null is a bug, requireNonNull remains the honest tool.
Follow-up: What separates a soft null (substitute) from a hard null (reject)?
Why does the index-check family exist?+
To give custom container classes the same fail-fast bounds behaviour and exact exception messages as the JDK collections: checkIndex for single indexes, checkFromIndexSize for ranges.
The message includes the numbers, which turns bug reports from 'something threw' into 'the caller asked for index 5 of a 3-element list'. Implementing List or extending AbstractList without these checks produces subtly wrong containers that the skeleton's other methods will trust.
public String get(int index) { Objects.checkIndex(index, size); return items.get(index); }
Common misconception: That the JVM checks array access so containers need nothing. Plain arrays do; your list-like class's own indexing is your contract to enforce.
Follow-up: Which exception type do the checks throw, and why that one?