Reputation: 17589
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?
Upvotes: 4
Views: 243
Reputation: 29359
Since we have only one instance of a .class object for each typed class, all references will be pointing to this same object (of Object.class) and hence will have the same hashcode (as the underlying object is same)
Upvotes: 2
Reputation: 1500515
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.
Upvotes: 5
Reputation: 500357
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.
Upvotes: 2