HashCode for Generic objects in Java

不羁岁月 提交于 2020-01-11 06:56:27

问题


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:


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.




回答2:


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.




回答3:


Java has a default Object.hashCode() implementation.

As much as is reasonably practical, the hashCode method defined by class Object 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.



来源:https://stackoverflow.com/questions/38596132/hashcode-for-generic-objects-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!