QUESTIONS & ANSWERS
JAVA
What is hash code in JAVA?
In Java, a hash code is a numeric value that is generated for an object by the hashCode()
method, which is defined in the Object
class and can be overridden in subclasses. The primary purpose of a hash code is to provide a way to efficiently store and retrieve objects in data structures such as hash tables.
Here's how it works:
-
Hash Codes for Equality Checking: Hash codes are commonly used in conjunction with the
equals()
method to determine if two objects are equal. When you override theequals()
method in your custom class, it's recommended to also override thehashCode()
method. If two objects are equal according to theirequals()
method, their hash codes should be equal as well. -
Hash Tables and Collections: Hash codes are used as keys to store objects in hash-based data structures like hash maps or hash sets. When you add an object to a hash-based collection, its hash code is computed and used to determine the index or bucket where the object should be stored. This enables efficient retrieval of objects from the collection.
-
Performance: Hash codes play a crucial role in the performance of hash-based data structures. If hash codes are well-distributed across the range of possible values and collisions (two different objects having the same hash code) are minimized, the data structure can provide constant-time average lookup and insertion operations.
Here's an example of how you might override the hashCode()
method in a Java class:
public class Person {
private String name;
private int age;
// Constructor, getters, setters, and other methods...
@Override
public int hashCode() {
int result = 17; // Start with a prime number
result = 31 * result + name.hashCode(); // Combine with attributes
result = 31 * result + age;
return result;
}
}
In this example, the hash code is computed by combining the hash codes of the name
attribute and the age
attribute using some prime numbers (17 and 31, which are commonly used in hash code calculations).
Remember that when you override the hashCode()
method, you should ensure that objects that are considered equal according to their equals()
method also produce the same hash code. Failing to do so can lead to unexpected behavior when using hash-based collections.