Library contents

Groovy String.hashCode

Compute Java’s integer content hash, as used by hash-based collections.

A simple example

String.hashCode

  1. Start with "A"
  2. Do this Calculate the string hash
  3. Result 65
For a one-character Java string, its hash equals the numeric value of that character.

Syntax

Groovy syntax
public int hashCode()
Run these examples in Groovy

Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.

groovy Lesson.groovy

Check a map key after decoding

A catalog imports a key from a scanner and looks it up using a separately decoded copy. Verify what happens to the hash when both strings contain exactly the same characters.

From the programprintln (new String("tea").hashCode() == "tea".hashCode())
Resulttrue
Lesson.groovy
println (new String("tea").hashCode() == "tea".hashCode())
Output
true

Equal String keys have equal hashes.

Advertisements

Test a collision in a catalog exercise

A catalog uses text as a lookup key and also computes a hash for indexing. Compare the keys themselves when deciding identity, because two different labels can share a hash value.

From the programprintln ("Aa".hashCode() == "BB".hashCode())
First output linetrue
Lesson.groovy
println ("Aa".hashCode() == "BB".hashCode())
println "Aa".equals("BB")
Output
true
false

Equal hashes do not establish equality.

Read a parcel sorting code

The depot scans a parcel marked NC-17. A Java-based scanner logs the String hash of the complete identifier for a diagnostic comparison. What decimal hash does it record?

GivenNC-17
Worked result74075454

What to watch for

Distinct strings can have the same hash. Use equals to establish identity and avoid using hashCode for secrets.

Documentation for String.hashCode