Reputation: 2681
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).
Upvotes: 0
Views: 399
Reputation: 129507
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 JavaTM programming language.)
Upvotes: 2
Reputation: 425013
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.
Upvotes: 1