I understand the idea of hashCode and why it's needed. However I'm confused about how hashCode is calculated for a Generic object. So here's my questions. If I've a String, I'd probably use the following function to calculate the hashCode,
int hash = 7;
for (int i = 0; i < strlen; i++) {
hash = hash*31 + charAt(i);
}
But say I've the following object,
class Node<K, V> {
private K key;
private V value;
private Node<K, V> next;
}
My IDE generates an automated hashCode function for this,
@Override
public int hashCode() {
int result = key != null ? key.hashCode() : 0;
result = 31 * result + (value != null ? value.hashCode() : 0);
result = 31 * result + (next != null ? next.hashCode() : 0);
return result;
}
My questions is since Key and Value are generic,what does key.hashCode() do?
How does this method work?
K and V are the parametrized types of your Node object.
As such, hashCode will be invoked on the actual types.
For instance a Node<String, Integer> will have String#hashCode and Integer#hashCode invoked respectively.
If you're parametrizing it with custom objects, either their own implementation of hashCode or their parent's implementation of hashCode will be invoked, up to Object#hashCode, which is a native (i.e. platform-dependent) implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With