Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashCode for Generic objects in Java

Tags:

java

hashcode

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?


1 Answers

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.

like image 186
Mena Avatar answered Mar 09 '26 16:03

Mena