Junior — Middle
How is the process of obtaining a hash code implemented in an object?
sobes.tech AI
Answer from AI
The process of obtaining an object's hash code in Android (Java/Kotlin) is implemented through the hashCode() method, which returns an integer value representing the object.
By default, the hashCode() method in the Object class returns a value based on the internal memory address of the object, but for user-defined classes, it is recommended to override this method to ensure correct comparison and usage in collections such as HashMap.
Example of overriding hashCode() along with equals():
@Override
public int hashCode() {
int result = 17;
result = 31 * result + (field1 != null ? field1.hashCode() : 0);
result = 31 * result + field2;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
MyClass other = (MyClass) obj;
return Objects.equals(field1, other.field1) && field2 == other.field2;
}
Here, hashCode() computes the hash based on the object's field values, allowing the object to be used correctly in hash data structures.