In Java, the hashCode()
method is a method of the Object
class that returns an integer value representing the hash code of an object. It is widely used in hash-based collections like HashMap
, HashSet
, and Hashtable
. Every object in Java inherits the hashCode()
method from the Object
class, but it is often overridden for custom classes to improve performance in hash-based collections.
hashCode()
in the Integer
class
The Integer
class, which is a part of java.lang
, overrides the hashCode()
method from the Object
class to return the int value itself. This makes sense because the hash code for integers can simply be the integer value, as it’s already a primitive type and doesn’t require additional processing.
Method Signature:
public int hashCode()
- The method returns an
int
value, which is the hash code of the integer object.
Usage in the Integer
class:
For Integer
, the hashCode()
method simply returns the integer value stored in the object, as Integer
is a wrapper class around the primitive int
.
Example:
public class IntegerHashCodeExample {
public static void main(String[] args) {
Integer num1 = new Integer(42);
Integer num2 = new Integer(42);
Integer num3 = new Integer(99);
// Printing hash codes of Integer objects
System.out.println("HashCode of num1: " + num1.hashCode()); // Output: 42
System.out.println("HashCode of num2: " + num2.hashCode()); // Output: 42
System.out.println("HashCode of num3: " + num3.hashCode()); // Output: 99
// Checking if two Integer objects with the same value have the same hash code
System.out.println("Hash codes of num1 and num2 are equal: " + (num1.hashCode() == num2.hashCode())); // Output: true
}
}
Explanation:
- In the example above, the
hashCode()
method of theInteger
class returns the integer value itself (42
fornum1
andnum2
, and99
fornum3
). - Since both
num1
andnum2
store the value42
, they return the same hash code, demonstrating that twoInteger
objects with the same value have the same hash code.
Key Points About hashCode()
in Integer
:
hashCode()
Returns the Integer Value:- For
Integer
, thehashCode()
method returns theint
value directly, which is stored inside theInteger
object. - For example,
Integer x = 42;
would return42
when callingx.hashCode()
.
- For
- Consistency:
- The
hashCode()
method for theInteger
class always returns the same value as long as the value of the integer object doesn’t change. This ensures consistency in collections likeHashMap
orHashSet
.
- The
- Equality and Hash Code:
- The
hashCode()
method must fulfill the contract ofequals()
andhashCode()
. If two objects are considered equal (i.e.,x.equals(y)
returnstrue
), they must have the same hash code. However, it is not necessary for two objects with the same hash code to be equal, though it is a desirable property for performance reasons.
- The