Sobes.tech
Junior — Middle

Is a unique hash code automatically provided to each object in Java, or does it only oblige the developer to implement it manually?

sobes.tech AI

Answer from AI

In Java, each object is provided with a unique hash code by default through the hashCode() method, which is implemented in the Object class. Developers are not required to implement this method themselves if the standard implementation is suitable.

However, if a class overrides the equals() method, it is recommended to also override hashCode() to ensure correct behavior in collections such as HashMap or HashSet.

Example of overriding:

@Override
public int hashCode() {
    return Objects.hash(field1, field2);
}