Groovy String.hashCode
Compute Java’s integer content hash, as used by hash-based collections.
A simple example
String.hashCode
- Start with "A"
- Do this Calculate the string hash
- Result 65
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.groovyCheck 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.
println (new String("tea").hashCode() == "tea".hashCode())
true
Equal String keys have equal hashes.
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.
println ("Aa".hashCode() == "BB".hashCode())
println "Aa".equals("BB")
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?
What to watch for
Distinct strings can have the same hash. Use equals to establish identity and avoid using hashCode for secrets.