java:用 == 或 .equals() 比较类:有区别吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5997801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:53:51  来源:igfitidea点击:

java: comparing classes with == or .equals(): is there a difference?

javaclassequality

提问by Jason S

Possible Duplicate:
Does Java guarantee that Object.getClass() == Object.getClass()?

可能的重复:
Java 是否保证 Object.getClass() == Object.getClass()?

I know you're supposed to use equals()in general, but is there any way two Class<?>objects could be equal with equals()but not equal with ==?

我知道你应该equals()在一般情况下使用,但是有什么办法Class<?>可以让两个对象等于equals()但不等于==

edit: I am specifically looking to find out whether two class objects exist such that

编辑:我特别想找出两个类对象是否存在

Class<?> cl1 = ...
Class<?> cl2 = ...
cl1.equals(cl2)    ->  true
cl1 == cl2         ->  false

This does notseemed to be covered by the possible duplicate question. (which is closely related)

这似乎没有包含在可能的重复问题中。(密切相关)

Also it may notbe true that the class objects were obtained by someObject.getClass()-- it could be that one was the result of Class.forName(...)and the other from some series of reflective actions like Method.getReturnType().

此外,类对象是通过以下方式获得的也可能不是真的someObject.getClass()——它可能是一个是Class.forName(...)某些系列反射动作的结果,另一个是像Method.getReturnType().

回答by Satish

All objects have both identity (the object's location in memory) and state (the object's data). The == operator always compares identity. The default implementation of equals compares identity as well.

所有对象都有身份(对象在内存中的位置)和状态(对象的数据)。== 运算符总是比较身份。equals 的默认实现也比较身份。

For a fuller explanation: http://www.javapractices.com/topic/TopicAction.do?Id=17

更全面的解释:http: //www.javapractices.com/topic/TopicAction.do?Id =17