简体   繁体   中英

HashSet of class objects. What is hashed?

I notice that in Java, you can create a HashSet that contains even objects. 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 -

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? There are three different fields (and possibly none of them might be primitives).

The "hash function" that sets and maps use is hashCode() . Unless you explicitly override hashCode() , the implementation as defined in Object will be used. 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. (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.)

There is only one class object in the JVM for a given class.

The hash code of class objects is the "identify hash" - as per the implementation in Object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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