OOP中的身份和平等有什么区别? [英] What is the difference between identity and equality in OOP?
本文介绍了OOP中的身份和平等有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
OOP(面向对象的编程)中的身份和平等有什么区别?
What is the difference between identity and equality in OOP (Object Oriented Programming)?
推荐答案
-
身份:变量持有
相同实例作为另一个变量。identity: a variable holds the same instance as another variable.
相等:两个不同的对象可以互换使用
。他们通常
有相同的ID。equality: two distinct objects can be used interchangeably. they often have the same id.
例如:
Integer a = new Integer(1); Integer b = a;
a
与<$ c $相同C> b 。在Java中,使用
==
测试身份。例如,if(a == b)
。In Java, identity is tested with
==
. For example,if( a == b )
.Integer c = new Integer(1); Integer d = new Integer(1);
c
等于但与d
。当然,两个相同的变量总是相等的。
Of course, two identical variables are always equal.
在Java中,相等性由
等于
方法定义。请记住,如果您实现等于您还必须实现 hashCode 。In Java, equality is defined by the
equals
method. Keep in mind, if you implement equals you must also implement hashCode.这篇关于OOP中的身份和平等有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文