简体   繁体   English

HashSet类对象。 什么是哈希?

[英]HashSet of class objects. What is hashed?

I notice that in Java, you can create a HashSet that contains even objects. 我注意到在Java中,您可以创建一个包含偶数对象的HashSet。 For example, you could create a class (say class1) that contains an int, double and array as variables within it and then you can say - 例如,您可以创建一个包含int,double和array作为变量的类(例如class1),然后可以说-

HashSet<class1> = new HashSet<>();

It's clear that in the HashSet of an integer, a hash function must be used that takes the integer as input and tells the function which bucket to store it in. But for this class1 variable, what exactly is hashed? 显然,在整数的HashSet中,必须使用将整数作为输入并告诉该函数将其存储在哪个存储桶中的哈希函数。但是对于此class1变量,到底是什么哈希呢? There are three different fields (and possibly none of them might be primitives). 存在三个不同的字段(可能都不是原语)。

The "hash function" that sets and maps use is hashCode() . 设置和映射使用的“哈希函数”是hashCode() Unless you explicitly override hashCode() , the implementation as defined in Object will be used. 除非您显式重写hashCode() ,否则将使用Object定义的实现。 That is, a hash based solely on reference and not at all on the fields will be produced. 即,将产生仅基于引用而不完全不基于字段的哈希。

From the link above: 从上面的链接:

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. 在合理可行的范围内,由Object类定义的hashCode方法确实为不同的对象返回不同的整数。 (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 TM programming language.) (通常通过将对象的内部地址转换为整数来实现,但是Java TM编程语言不需要此实现技术。)

There is only one class object in the JVM for a given class. 对于给定的类,JVM中只有一个类对象。

The hash code of class objects is the "identify hash" - as per the implementation in Object. 根据对象中的实现,类对象的哈希码是“识别哈希”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM