How would this value help in decreasing collisions?

Hash collision is primarily achieved by a good distribution across the whole hash range (here the integer type).

By defining 0 as the initial value for calculating the hash result, you have a somewhat restricted distribution in a small range. Objects that differ in a minor way - maybe in some field only - produce hash codes that are not far away from each other. This makes hash collisions more likely.

By defining a non-zero initial value, you simply increase the gaps between calculated hash codes for objects that differ only in a minor way. So you better utilize the hash range and effectively make hash collisions more unlikely.

What does he means by saying that the exact value returned by hashCode is a function of the instance value?

It simply means that you should calculate the hash code by using the object's value, i.e. the values of its fields. You already did it in your example, and I think that you already implicitly understood it.

But: Joshua Bloch intended to say something else with this paragraph: He wanted to warn you about not documenting the exact function how the hash code is calculated. If you do so, you restrict yourself to not being able anymore to change the implementation in future releases because some users might expect a specific implementation, and you would break some code depending on yours.

Answer from Seelenvirtuose on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ map-hashcode-method-in-java-with-examples
Java Map hashCode() Method - GeeksforGeeks
July 11, 2025 - Note: The hashCode() method generates a hash code based on the objects's memory address or internal data. ... Return Type: This method returns an integer value that represent the hash code of the object.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ method-class-hashcode-method-in-java
Method Class | hashCode() Method in Java - GeeksforGeeks
July 11, 2025 - Hashcode is a unique code generated by the JVM at time of object creation. It can be used to perform some operation on hashing related algorithms like hashtable, hashmap etc.
Discussions

Can someone ELI5 the hashcode() method for me?
This is not material that any 5 year old would understand. HashCode is a 'helper' function that allows collections like HashMap to guess where they stored an object. Lets say you have a list of strings (apple, analog, bee and data) and you want to 'test' if the string "cider" is in that list. With a simple list you would have to, worst case, check all the items in the list. In this case 4. Hashmaps/sets use the 'trick' that objects can give a short number that is calculated from their contents. Lets say we simply use the alphabet position of the first character of the string. So apple and analog would be 1, bee would be 2, data would be 4. We would then create a bunch of lists based on those codes. We would stuff apple and analog into list 1, bee in list 2, data in list 4. If we were then to test "cider" which would have code 3 we would not have to check any list because we know there isn't even a list with code 3, let alone any strings in there. Same if we wanted to test "art": we know it also has hashcode 1 so we only need to test a list of 2 items instead of all 4 items. This is as simple as I can explain what a HashSet / Map does and why it needs a hashcode. In reality how it decides to create these internal lists and how a hashcode is made is a bit more complex but it essentially works like this. More on reddit.com
๐ŸŒ r/java
18
5
November 6, 2014
Designing hashCode method Java - Stack Overflow
I'm studying Item 9, Effective Java [Always override hashcode() when you override equals]. I have a few queries regarding the points made by author : The author says: A nonzero initial value is us... More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - What is the hashCode for a custom class having just two int properties? - Stack Overflow
In Java, I have a class that represents a point with int coordinates public class Point { int x = -1; int y = -1; public Point (int xNew, int yNew) { x = xNew; y = yNew; }... More on stackoverflow.com
๐ŸŒ stackoverflow.com
What is the use of hashCode in Java? - Stack Overflow
Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ core java โ€บ guide to hashcode() in java
Guide to hashCode() in Java | Baeldung
December 8, 2025 - Java provides a number of data structures for dealing with this issue specifically. For example, several Map interface implementations are hash tables. When using a hash table, these collections calculate the hash value for a given key using the hashCode() method.
๐ŸŒ
SHA1 Online
sha1-online.com
SHA1 online
sha1 online hash generator. The tool generates hashes also for the following algorithms: md5; md2; md4; sha256; sha384; sha512; ripemd128; ripemd160; ripemd256; ripemd320; whirlpool; tiger128,3; tiger160,3; tiger192,3; tiger128,4; tiger160,4; tiger192,4; snefru; gost; adler32; crc32; crc32b; ...
๐ŸŒ
Reddit
reddit.com โ€บ r/java โ€บ can someone eli5 the hashcode() method for me?
r/java on Reddit: Can someone ELI5 the hashcode() method for me?
November 6, 2014 -

I get the equals() method, and have used it to specify a more specifc equality check on objects, but I still can't grasp why the need for hashcode!

Any good explanations appreciated.

Top answer
1 of 4
7
This is not material that any 5 year old would understand. HashCode is a 'helper' function that allows collections like HashMap to guess where they stored an object. Lets say you have a list of strings (apple, analog, bee and data) and you want to 'test' if the string "cider" is in that list. With a simple list you would have to, worst case, check all the items in the list. In this case 4. Hashmaps/sets use the 'trick' that objects can give a short number that is calculated from their contents. Lets say we simply use the alphabet position of the first character of the string. So apple and analog would be 1, bee would be 2, data would be 4. We would then create a bunch of lists based on those codes. We would stuff apple and analog into list 1, bee in list 2, data in list 4. If we were then to test "cider" which would have code 3 we would not have to check any list because we know there isn't even a list with code 3, let alone any strings in there. Same if we wanted to test "art": we know it also has hashcode 1 so we only need to test a list of 2 items instead of all 4 items. This is as simple as I can explain what a HashSet / Map does and why it needs a hashcode. In reality how it decides to create these internal lists and how a hashcode is made is a bit more complex but it essentially works like this.
2 of 4
3
Generates a uniquish number for use in hashtables that utilize the bucket hash method. In simplest terms, you allocate an array of arrays. The outer array is indexed by hashcodes and the inner arrays (buckets) are just lists of every object that has that hashcode. Outer array lookups are constant time, buckets are linear. When 2 objects have the same hashcode that's called a collision. Choosing a hash function with fewest collisions creates a very large outer array with very short inner arrays. That is fast, but memory intensive. Lots of collisions means you can pack the data tighter, but you'll have larger buckets so slower lookups. That's why large scale applications need to design hashcodes carefully.
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ ref_string_hashcode.asp
Java String hashCode() Method
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Server Java Syllabus Java Study Plan Java Interview Q&A Java Certificate ... The hashCode() method returns the hash code of a string.
Find elsewhere
Top answer
1 of 5
1

How would this value help in decreasing collisions?

Hash collision is primarily achieved by a good distribution across the whole hash range (here the integer type).

By defining 0 as the initial value for calculating the hash result, you have a somewhat restricted distribution in a small range. Objects that differ in a minor way - maybe in some field only - produce hash codes that are not far away from each other. This makes hash collisions more likely.

By defining a non-zero initial value, you simply increase the gaps between calculated hash codes for objects that differ only in a minor way. So you better utilize the hash range and effectively make hash collisions more unlikely.

What does he means by saying that the exact value returned by hashCode is a function of the instance value?

It simply means that you should calculate the hash code by using the object's value, i.e. the values of its fields. You already did it in your example, and I think that you already implicitly understood it.

But: Joshua Bloch intended to say something else with this paragraph: He wanted to warn you about not documenting the exact function how the hash code is calculated. If you do so, you restrict yourself to not being able anymore to change the implementation in future releases because some users might expect a specific implementation, and you would break some code depending on yours.

2 of 5
1

See this example:

    String a = "Abc";
    String b = "Abc";
    String c = "Pqr";
    System.out.println(" "+a.hashCode()+" "+b.hashCode()+" "+c.hashCode());

Output: 65602 65602 80497

Which clearly shows that hashCode() of string depends on values.

Extract from hashCode() documentation:
int java.lang.String.hashCode()

Returns a hash code for this string. The hash code for a String object is computed as

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)

๐ŸŒ
Quora
quora.com โ€บ How-does-Java-implement-hashCode-for-Integer-Double-and-Long
How does Java implement hashCode() for Integer, Double, and Long? - Quora
Answer (1 of 2): Probably with some variation of the algorithms given by Joshua Bloch in his book Effective Java. Wait, did you mean to include the 32-bit integer wrapper in your question? Since the hash code function is supposed to return a 32-bit integer, in this case it might as well return t...
Top answer
1 of 8
66

You can't change the type of hashCode, nor should you want to.

I'd just go with something like:

public int hashCode() {
    return x * 31 + y;
}

Note that this means that (a, b) is different to (b, a) for most cases (unlike e.g. adding or XOR-ing). This can be useful if you often end up with keys for the "switched" values in real life.

It isn't unique - but hash codes don't have to be. They just have to be the same for equal values (for correctness), and (for efficiency) "usually" different for non-equal values, with a reasonable distribution.

In general, I usually follow the same kind of pattern as Josh Bloch suggests in Effective Java:

public int hashCode() {
    int hash = 17;
    hash = hash * 31 + field1Hash;
    hash = hash * 31 + field2Hash;
    hash = hash * 31 + field3Hash;
    hash = hash * 31 + field4Hash;
    ...
    return hash;
}

Where field1Hash would be the hash code for reference type fields (or 0 for a null reference), the int itself for int values, some sort of hash from 64 bits to 32 for long etc.

EDIT: I can't remember the details of why 31 and 17 work well together. The fact that they're both prime may be useful - but from what I remember, the maths behind why hashes like this are generally reasonable (though not as good as hashes where the distribution of likely values is known in advance) is either difficult or not well understood. I know that multiplying by 31 is cheap (shift left 5 and subtract the original value)...

2 of 8
14

I know that it is ok for non-equal objects to have the same hashcodes. However, the more collisions, the worse the performance will be (for example, in a hash table).

As far as I know, the best mapping from Zยฒ โ†’ Z is the "elegant pairing function" (google it). Here is the implementation

// x,y must be non-negative
int elegant(int x, int y) {
    return x < y ? y * y + x : x * x + x + y;
}


// returns a unique number for every x,y pair
int elegantSigned(int x, int y) {
    if (x < 0) {
        if (y < 0)
            return 3 + 4 * elegant(-x - 1, -y - 1);
        return 2 + 4 * elegant(-x - 1, y);
    }
    if (y < 0)
        return 1 + 4 * elegant(x, -y - 1);
    return 4 * elegant(x, y);
}

This will begin to overlap as soon as you get multiplication overflow. If the absolute value of x and y is less than about 46000, then this will have zero hash collisions.

๐ŸŒ
CodeGym
codegym.cc โ€บ java blog โ€บ java objects โ€บ java hashcode()
What is Java hashcode
January 8, 2025 - If two objects are equal, their hashcodes are the same. The reverse is not true. If the hash codes are different, then the objects are not equal for sure. Different objects may have the same hash code. However, it is a very unlikely event. At this point, we have a collision, a situation, where we can lose data. The "proper" hash function minimizes the probability of collisions. In Java hash function is usually connected to hashCode() method.
๐ŸŒ
Wikipedia
en.wikipedia.org โ€บ wiki โ€บ Kotlin
Kotlin - Wikipedia
2 days ago - Kotlin's data class construct defines classes whose primary purpose is storing data, similar to Java's record types. Like Java's record types, the construct is similar to a regular class, except that the key methods equals, hashCode, and toString are automatically generated from the class's properties.
๐ŸŒ
Codefinity
codefinity.com โ€บ blog โ€บ How-equals()-and-hashCode()-Work-in-Java-and-Why-Following-Their-Contract-Matters
How equals() and hashCode() Work in Java and Why Following Their Contract Matters
The hashCode() method returns an integer hash code for an object, which is used in hash-based collections like HashMap and HashSet for efficient lookup and object organization.
Top answer
1 of 7
270

hashCode() is used for bucketing in Hash implementations like HashMap, HashTable, HashSet, etc.

The value received from hashCode() is used as the bucket number for storing elements of the set/map. This bucket number is the address of the element inside the set/map.

When you do contains() it will take the hash code of the element, then look for the bucket where hash code points to. If more than 1 element is found in the same bucket (multiple objects can have the same hash code), then it uses the equals() method to evaluate if the objects are equal, and then decide if contains() is true or false, or decide if element could be added in the set or not.

2 of 7
41

From the Javadoc:

Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.

  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java programming language.)

๐ŸŒ
Falkhausen
falkhausen.de โ€บ docs โ€บ Java-10 โ€บ java.security โ€บ CodeSource โ€บ m0.html
Untitled
hashCode () Overriding: java.lang.Object ยท Returns the hash code value for this object. Returns: a hash code value for this object.
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 321515 โ€บ java โ€บ HashCode
What is HashCode [Solved] (Java in General forum at Coderanch)
May 9, 2000 - Sometimes a box will have more ... a whole pile of cabbages, peas , banjos and rhinoceroses. That's a hash code. A way of getting a number from an object so it can be stored in a Hashtable. In Java a hash code can be any integer, and each object type is responsible for ...
๐ŸŒ
Medium
medium.com โ€บ @AlexanderObregon โ€บ what-is-hashcode-in-java-a-simple-guide-a3b95d6ebae4
What are Hashcodes in Java? A Simple Guide
April 2, 2024 - Imagine a hashcode as a digital fingerprint for an object; just as no two people have the same fingerprints, the ideal scenario is that no two objects share the same hashcode. However, due to the finite size of integer values in Java, different objects can indeed end up with identical hashcodes, leading to whatโ€™s known as a collision.
Top answer
1 of 4
55

You're breaking one of the hashCode() taboos; you're using its output as a key identifier. That's wrong.

You see, the output of hashCode() (in its default implementation) is a 32-bit unsigned integer, that's roughly 4 billion unique hashCodes. Sounds quite a lot? Well, not so much. Applying the birthday problem in this case shows as that with about 77000 objects, you have about 50% chance of collision. 50% chance of two objects having the the same hashCode.

Another issue is that the implementation of hashCode() can change from one Java version to the other. It's not meant to be permanent identifier of an object, so there's nothing forcing it to be consistent across versions.

If you insist on using hashes as object identifiers, then it's much better to have your own method instead of hashCode() to use for your key identifiers (for example, getMySpecialHashKey(). You can uses something like MessageDigest.getInstance("SHA-256") to digest the object into a nice 256-bit key.

My recommendation: Ditch the whole idea of hashing the object and rather generate a random identifier for your object when you construct it. Something along the lines of (in Java)

SecureRandom secRand = new SecureRandom();
byte[] objIdBytes = new byte[16]; //128-bit
secRand.nextBytes(objIdBytes);
String objId = Base64.encodeBase64String(objIdBytes); //Here's your ID

You also seem to bind access to an object only to knowledge of its key. That's also wrong. A proper permission-based model with proper authentication and authorization is needed.

2 of 4
31

Java hashCode() was never intended to be used like this. Don't do ever it! It is even legal (while not recommended) for all instances of a class to return the same hashCode. The contract in Java is "two objects that are considered equal must have same hashcode". No more, no less. It would for example be valid to return hashcode 1 for all uneven numbers and 0 for even ones.

hashCode is used for faster lookup in Collections such as HashMap and collisions are expected.

Many classes define their own version of hashCode(), and if you know the code, you can often easily tell or guess the hashcode.

So, this is absolutely insecure.

๐ŸŒ
Medium
medium.com โ€บ @AlexanderObregon โ€บ how-javas-equals-and-hashcode-methods-work-together-da27332bb742
How Javaโ€™s equals() and hashCode() Work Together | Medium
February 22, 2025 - These methods are built into the ... if two objects should be treated as the same, while hashCode() generates a numerical representation of an object....
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ hashcode() in java
HashCode() in Java | Java hashcode Method - Scaler Topics
May 1, 2024 - This hashcode value refers to its bucket, and the corresponding value is retrieved from it. Hashing is a Computer Science concept that maps an object or entity to an integer. The hash value of an object is an integer value that is computed using the properties of that object. Every object in Java inherits the hashCode() and equals() method.