Java Materials
← Core Java · Chapter 3

Object contracts, strings and value types

Identity answers whether two references refer to one object. Equality answers whether they represent equal values under the type’s rules. Design a stable equality boundary before choosing a map key, comparator or serialization format.

Equality, hashing and mutable keys

Definition:

Equality defines when two values represent the same logical key.

Explanation:

Hash lookup uses a hash to select a candidate bin and equals to distinguish candidates within it.

Illustration image:

Equality, hashing and mutable keys. Key hash · HashMap bin · Equality check · Matching entryEquality, hashing and mutable keysSource or actorKey hashFirst boundaryHashMap binInspected stateEquality checkObservable effectMatching entry
Key hash · HashMap bin · Equality check · Matching entry

Example:

Worked Java example · see surrounding context in notes
record OrderKey(String tenant, long id) {}
var map = new java.util.HashMap<OrderKey,String>();
map.put(new OrderKey("retail",42),"paid");
System.out.println(map.get(new OrderKey("retail",42)));

Expected behavior. A different object with equal components retrieves paid.

Internal working:

If fields controlling equality change after insertion, a subsequent lookup can search the wrong bin. Represent cache keys as normalized immutable values, and include disambiguators such as tenant or region when that is part of identity.

Interview questions:

How can a mutated key remain in a HashMap but fail lookup?

Lookup uses the key’s current hash and may inspect a different bin from the one used at insertion.

Ordering, scale and normalization

Definition:

Ordering compares values for navigation and sorting, while equality identifies logical duplicates in hash collections.

Explanation:

BigDecimal.equals includes scale, while its natural order compares numeric value.

Illustration image:

Ordering, scale and normalization. 2.0 · scale 1 · 2.00 · scale 2 · HashSet: two entries · TreeSet: one entryOrdering, scale and normalizationSource or actor2.0 · scale 1First boundary2.00 · scale 2Inspected stateHashSet: two entriesObservable effectTreeSet: one entry
2.0 · scale 1 · 2.00 · scale 2 · HashSet: two entries · TreeSet: one entry

Example:

Worked Java example · see surrounding context in notes
var a = new java.math.BigDecimal("2.0");
var b = new java.math.BigDecimal("2.00");
System.out.println(new java.util.HashSet<>(java.util.List.of(a,b)).size());
System.out.println(new java.util.TreeSet<>(java.util.List.of(a,b)).size());

Expected behavior. HashSet prints 2; TreeSet prints 1.

Internal working:

TreeSet treats comparison zero as one ordering slot, but HashSet uses equals. Define scale at API and persistence boundaries with an explicit rounding mode. Never round silently before a domain decision that depends on the original precision.

Interview questions:

Why does TreeSet give one entry for 2.0 and 2.00?

BigDecimal natural ordering compares numeric values; equals also compares scale.

Unicode and testable time

Definition:

A Unicode code point represents a scalar value; Clock provides an injectable time source.

Explanation:

One UTF-16 char may be half a supplementary character.

Illustration image:

Unicode and testable time. Code point U+1F600 · High surrogate · Low surrogate · UTF-8 bytesUnicode and testable timeSource or actorCode point U+1F600First boundaryHigh surrogateInspected stateLow surrogateObservable effectUTF-8 bytes
Code point U+1F600 · High surrogate · Low surrogate · UTF-8 bytes

Example:

Worked Java example · see surrounding context in notes
var fixed = java.time.Clock.fixed(java.time.Instant.parse("2026-01-01T00:00:00Z"),
    java.time.ZoneOffset.UTC);
System.out.println(java.time.Instant.now(fixed));
System.out.println("😀".codePointCount(0, "😀".length()));

Expected behavior. The time is reproducible. The emoji is one code point and two UTF-16 code units.

Internal working:

A code point is also not necessarily a full user-visible grapheme. Match your boundary to the actual requirement. For time, separate elapsed Duration from local calendar Period; adding a local day across DST can differ from adding 24 hours. Inject Clock to make expiry tests deterministic.

Interview questions:

Why is String.length() not a reliable character count?

It counts UTF-16 code units. A supplementary code point can occupy two units, and a displayed grapheme may contain several points.

Reference subtopics

Object methods and hash keys

getClass reports runtime type. toString should help diagnosis without leaking secrets. equals must be reflexive, symmetric, transitive, consistent and false for null. Equal values must share hashCode. A mutable hash key can become unfindable after insertion. Identity-based lookup is special-purpose and uses reference identity by design.

Comparable and Comparator

Comparable gives natural ordering. Comparator.comparing and thenComparing make sort keys explicit. If a comparator returns zero for unequal objects, a sorted set treats them as one ordering key. Compare numeric values with Integer.compare or comparingInt to avoid subtraction overflow.

Strings and joining

String is immutable. Literals and constant string expressions may be interned; intern returns a canonical pooled string. Use equals for text. Prefer StringBuilder for repeated single-threaded appends, StringJoiner for delimiter-aware output, and understand that synchronized StringBuffer methods do not automatically make a multi-call sequence atomic.

Unicode and encoding

A char stores one UTF-16 code unit. An emoji can require a surrogate pair, so String.length need not count code points or visible graphemes. Use codePoints for code-point logic and StandardCharsets.UTF_8 for explicit bytes. Do not truncate user-visible text by blindly cutting at a char boundary.

Money and time

BigInteger handles arbitrary-precision integers; BigDecimal handles decimal scale and rounding. equals includes scale, compareTo compares numeric value. For time, Instant identifies a timeline point, LocalDate a calendar date and ZonedDateTime zone-aware local time. Period is calendar-based; Duration is elapsed time. Test DST gaps and overlaps and inject Clock for reproducible expiry rules.

Run the complete Java labs ↗ · Java reference ↗