简体   繁体   中英

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

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.

由于每个类型化类只有一个.class对象实例,所有引用都将指向同一个对象(Object.class),因此将具有相同的哈希码(因为底层对象是相同的)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM