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

I want to create a hash map of classes like (Object.class). I wonder

Is Object.class considered equal to another Object.class?

Could there be another instance of Object.class that forces it to have another hashcode?

+4
source share
3 answers

The literal Object.class will always return the same link in the same classloader.

From section 15.8.2 of the JLS :

A class literal evaluates a Class object for a named type (or for void), as defined by the defining class loader for the class of the current instance.

Pay attention to a specific article ("the") in the above quote - there is only one Class object for any particular class, inside the same class loader.

So yes, you will get the same hash code because you will have two links to the same object.

+5
source

Inside this class loader, for each loaded class there is a single object of type Class .

x1.getClass() and x2.getClass() return the same reference if x1 and x2 are of the same dynamic type.

+2
source

Since for each typed class we have only one instance of the .class object, all links will point to the same object (Object.class) and, therefore, will have the same hash code (since the underlying object is the same)

+2
source

Source: https://habr.com/ru/post/1339071/


All Articles