Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do two classes of the same class have the same hashcode and are they considered equal?

Tags:

java

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?

like image 894
denniss Avatar asked Jan 20 '23 13:01

denniss


2 Answers

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.

like image 53
Jon Skeet Avatar answered Jan 23 '23 02:01

Jon Skeet


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.

like image 39
NPE Avatar answered Jan 23 '23 01:01

NPE