Java中的通用对象的HashCode [英] HashCode for Generic objects in Java

查看:96
本文介绍了Java中的通用对象的HashCode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解hashCode的想法以及为什么需要它。但是我对如何为Generic对象计算hashCode感到困惑。所以这是我的问题。如果我有一个String,我可能会使用以下函数来计算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;
}

我的IDE为此生成自动hashCode函数,

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;
}

我的问题是,因为Key和Value是通用的,<$ c $是什么c> key.hashCode()吗?
这个方法有用吗?

My questions is since Key and Value are generic,what does key.hashCode() do? How does this method work?

推荐答案

K V Node 对象的参数化类型。

K and V are the parametrized types of your Node object.

因此,将在实际类型上调用 hashCode

As such, hashCode will be invoked on the actual types.

例如 Node< String,Integer> 将有 String#hashCode 分别调用整数#hashCode

如果您使用自定义对象对其进行参数化,可以使用自己的 hashCode 实现,也可以使用其父实现<将调用code> hashCode ,最高为 Object#hashCode ,这是一个本机(即平台相关的)实现。

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.

这篇关于Java中的通用对象的HashCode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆