Java 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
class Main {
public static void main(String[] args) throws Exception {
System.out.println("A".hashCode());
}
}
65
Syntax
public int hashCode()
JDK 21 method signatures (1)
public int hashCode()Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaMatch a freshly scanned catalog key
A freshly scanned catalog key arrives as a separate object from the stored key. Check its text and lookup behavior before deciding whether the scanner has identified an existing item.
class Main {
public static void main(String[] args) throws Exception {
String scan = new String("A7");
System.out.println(scan.hashCode() == "A7".hashCode());
}
}
true
Equal strings have the same hash even when they are different objects.
See why equal hashes cannot identify customers
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.
class Main {
public static void main(String[] args) throws Exception {
String first = "Aa";
String second = "BB";
System.out.println((first.hashCode() == second.hashCode()) + " / " + first.equals(second));
}
}
true / false
These two different strings collide under Java’s string hash.
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.