简体   繁体   English

同一个类的两个类是否具有相同的哈希码,它们被认为是相同的吗?

[英]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). 我想创建类(Object.class)类的哈希映射。 I am wondering whether 我想知道是否

Object.class is considered equal to another Object.class? Object.class被认为等于另一个Object.class?

Can there be another instance of Object.class which leads it to have different hashcode? 可以有另一个Object.class实例导致它有不同的哈希码吗?

The literal Object.class will always return the same reference within the same classloader. 文字Object.class将始终在同一个类加载器中返回相同的引用。

From section 15.8.2 of the JLS : JLS第15.8.2节开始

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. 类文本计算为由当前实例的类的定义类加载器定义的命名类型(或void)的Class对象。

Note the definite article ("the") in the quote above - there's only one Class object for any particular class, within the same class loader. 请注意上面引用中的定冠词(“the”) - 在同一个类加载器中,任何特定类只有一个 Class对象。

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 . 在给定的类加载器中,对于每个加载的类,都有一个类型为Class对象。

x1.getClass() and x2.getClass() return the same reference as long as x1 and x2 have the same dynamic type. 只要x1x2具有相同的动态类型, x1.getClass()x2.getClass()返回相同的引用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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