I want to create a hashmap of classes like (Object.class). I am wondering whether
Object.class is considered equal to another Object.class?
Can there be another instance of Object.class which leads it to have different hashcode?
The literal Object.class
will always return the same reference within the same classloader.
From section 15.8.2 of the JLS:
A class literal evaluates to the Class object for the named type (or for void) as defined by the defining class loader of the class of the current instance.
Note the definite article ("the") in the quote above - there's only one Class
object for any particular class, within the same class loader.
So yes, you'll get the same hashcode - because you'll have two references to the same object.
Within a given class loader, for each loaded class there's a single object of type Class
.
x1.getClass()
and x2.getClass()
return the same reference as long as x1
and x2
have the same dynamic type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With