Reputation:
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?
Upvotes: 3
Views: 4120
Reputation: 19343
Java has a default Object.hashCode()
implementation.
As much as is reasonably practical, the
hashCode
method defined by classObject
does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java programming language.)
If hashCode()
is overriden in concrete classes of K and V, then exact overriding method will be called.
Upvotes: 0
Reputation: 4062
Java's Object
class has a .hashCode()
method (albeit one based on the reference, so not often one you want to use.) key.hashCode()
is thus guaranteed to exist, and can be dispatched correctly no matter what the specific type of this generic is. It will either use Object
's '.hashCode()` implementation, or a more specific one if available.
Upvotes: 0
Reputation: 48444
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.
Upvotes: 2