Java OOP 中的同一性和平等性有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1692863/
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-08-12 21:37:59  来源:igfitidea点击:

What is the difference between identity and equality in OOP?

javaoopobject

提问by sevugarajan

What is the difference between identity and equality in OOP (Object Oriented Programming)?

OOP(面向对象编程)中的同一性和相等性有什么区别?

采纳答案by Andreas Petersson

  • identity: a variable holds the sameinstance as another variable.

  • equality: two distinctobjects can be used interchangeably. they often have the same id.

  • 身份:一个变量与另一个变量拥有 相同的实例。

  • 相等:两个不同的对象可以互换使用。它们通常具有相同的 ID。

Identity

身份

For example:

例如:

Integer a = new Integer(1);
Integer b = a;

ais identical to b.

a与 相同b

In Java, identity is tested with ==. For example, if( a == b ).

在 Java 中,身份使用==. 例如,if( a == b )

Equality

平等

Integer c =  new Integer(1);
Integer d = new Integer(1);

cis equal but not identical to d.

c等于但不等同于d

Of course, two identical variables are always equal.

当然,两个相同的变量总是相等的。

In Java, equality is defined by the equalsmethod. Keep in mind, if you implement equalsyou must also implement hashCode.

在 Java 中,相等是由equals方法定义的。请记住,如果您实现equals,则还必须实现hashCode

回答by jitter

Identity means it is the same object instance while equality means the objects you compare are to different instances of an object but happen to contain the same data.

身份意味着它是同一个对象实例,而相等意味着您比较的对象是一个对象的不同实例,但碰巧包含相同的数据。

Illustration (in java)

插图(在java中)

Date a = new Date(123);
Date b = new Date(123);
System.out.println(a==b); //false
System.out.println(a.equals(b)); //true

So a and b are different instances (different allocations in memory) but on the "data" level they are equal.

所以 a 和 b 是不同的实例(内存中的不同分配),但在“数据”级别上它们是相等的。

回答by Antz

Identity determines whether two objects share the same memory address. Equality determines if two object contain the same state.

Identity 确定两个对象是否共享相同的内存地址。相等确定两个对象是否包含相同的状态。

If two object are identical then they are also equal but just because two objects are equal dies not mean that they share the same memory address.

如果两个对象相同,那么它们也相等,但仅仅因为两个对象相等并不意味着它们共享相同的内存地址。

There is a special case for Strings but that is off topic and you'll need to ask someone else about how that works exactly ;-)

字符串有一个特殊情况,但这是题外话,您需要向其他人询问它的工作原理;-)

回答by Pete Kirkham

In Java and similar languages which 'leak' the abstraction of a reference of an object, you can test whether two references refer to the same object. If they refer to the same object, then the references are identical. In Java, this is the ==operator.

在“泄漏”对象引用抽象的 Java 和类似语言中,您可以测试两个引用是否引用同一个对象。如果它们引用同一个对象,则引用是相同的。在 Java 中,这是==运算符。

There is also an equalsmethod which is used to test whether two objects have the same value, for example when used as keys of a HashSet(the hash code of equal objects should also be equal). Equal objects should have the same 'value' and semantics when used by client code.

还有一种equals方法用于测试两个对象是否具有相同的值,例如用作 a 的键时HashSet(相等对象的哈希码也应该相等)。当客户端代码使用时,相等的对象应该具有相同的“值”和语义。

Purer object-oriented languages do not have an identity comparison, as client code generally shouldn't care whether or not two objects have the same memory address. If objects represent the same real-world entity, then that is better modelled using some ID or key value rather than identity, which then becomes part of the equals contract. Not relying on the memory address of the object to represent real-world identity simplifies caching and distributed behaviour, and suppressing ==would remove a host of bugs in string comparison or some uses of boxing of primitives in Java.

更纯粹的面向对象语言没有身份比较,因为客户端代码通常不应该关心两个对象是否具有相同的内存地址。如果对象代表同一个现实世界的实体,那么最好使用一些 ID 或键值而不是身份来建模,然后身份成为 equals 合同的一部分。不依赖对象的内存地址来表示真实世界的身份简化了缓存和分布式行为,并且抑制==将消除字符串比较中的大量错误或 Java 中原语装箱的一些使用。

回答by Piskvor left the building

x == yis true only if there's the same object referenced by variables xand y.

x == y仅当变量x和引用相同的对象时才为真y

x.equals(y)depends on the implementation of x.equals(), and is usually less strict that the above, as it compares the content of the object. (In Java, if x.equals(y), it must also be true that x.hashCode() == y.hashCode();)

x.equals(y)取决于 的实现x.equals(),并且通常不如上述严格,因为它比较对象的内容。(在 Java 中,如果x.equals(y),那么 也一定是真的x.hashCode() == y.hashCode();

Example:

例子:

Integer w = new Integer(3);
Integer x = new Integer(1);
Integer y = x;
Integer z = new Integer(1);

// all of these evaluate to true
y.equals(x) // it's the same object, of course the content is same
x.equals(z) // different objects, same content (`1`)
z.equals(y)
!w.equals(x); // the content is different (`3` vs `1`)
!w.equals(y);
!w.equals(z);
x == y // same object
z != x // different objects
y != z
w != x

回答by Rakesh Juyal

For primitive types ( int , boolean , char, long , float ... )
== and != is equality test

For primitive types ( int , boolean , char, long , float ... )
== 和 != 是相等测试

and for Objects
== and != is identity test. [ it compares only the reference ]

and for Objects
== 和 != 是身份测试。[只比较参考]

equalsmethod is used for equality test of Objects [ it can be overridden to compare specific attributes]

equals方法用于对象的相等性测试[它可以被覆盖以比较特定属性]

i found an excellent article on this http://www.cs.cornell.edu/courses/cs211/2006sp/Lectures/L14-Comparison/L14cs211sp06.pdf

我在http://www.cs.cornell.edu/courses/cs211/2006sp/Lectures/L14-Comparison/L14cs211sp06.pdf上找到了一篇很棒的文章

http://ocw.mit.edu/NR/rdonlyres/Electrical-Engineering-and-Computer-Science/6-170Fall-2005/D659DC53-FB1D-403C-8E35-2CAECBED266E/0/lec12.pdf

http://ocw.mit.edu/NR/rdonlyres/Electrical-Engineering-and-Computer-Science/6-170Fall-2005/D659DC53-FB1D-403C-8E35-2CAECBED266E/0/lec12.pdf

Quote
I like pigs. Dogs look up to us. Cats look down on us. Pigs treat us as equals.:D
Sir Winston Churchill

引用
我喜欢猪。狗很看重我们。猫看不起我们。猪对我们一视同仁。:D
Sir Winston Churchill

回答by tangens

Identity:Two references to the same object (o1 == o2).

身份:对同一对象的两个引用 ( o1 == o2)。

Equality:The method o1.equals( o2 )returns true. This doesn't necessarily mean that the two objects contain (all) the same data.

相等:该方法o1.equals( o2 )返回true。这并不一定意味着两个对象包含(所有)相同的数据。

In theory it's possible to override a method equals()to return falseeven for identical objects. But this would break the specification of Object.equals():

从理论上讲,即使对于相同的对象,也可以覆盖一个方法equals()来返回false。但这会破坏以下规范Object.equals()

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.

equals 方法在非空对象引用上实现等价关系:

  • 它是自反的:对于任何非空引用值 x,x.equals(x) 应该返回 true。
  • 它是对称的:对于任何非空引用值 x 和 y,当且仅当 y.equals(x) 返回 true 时,x.equals(y) 才应返回 true。
  • 它是可传递的:对于任何非空引用值 x、y 和 z,如果 x.equals(y) 返回 true 并且 y.equals(z) 返回 true,那么 x.equals(z) 应该返回 true。
  • 它是一致的:对于任何非空引用值 x 和 y,x.equals(y) 的多次调用始终返回 true 或始终返回 false,前提是对象的 equals 比较中使用的信息没有被修改。
  • 对于任何非空引用值 x,x.equals(null) 应返回 false。

回答by Hyman

Identity concept is quite philosophical, that's why you shouldn't reconduce it just to references.

身份概念是非常哲学的,这就是为什么你不应该把它仅仅归结为引用。

You can say that two identities are the same if a change to the first is reflected on the second and vice-versa. Of course this includes also sharing the same memory address but in general while identity is related to the attributes of the object, equality is used to check whenever two objects are identical, but this doesn't include identity.

如果对第一个身份的更改反映在第二个身份上,则可以说两个身份相同,反之亦然。当然,这也包括共享相同的内存地址,但通常身份与对象的属性有关,相等性用于检查两个对象是否相同,但这不包括身份。

The viceversa is quite obvious, if two items have the same identity they are also equal (in equality terms of being interchangeable).

反之亦然很明显,如果两个项目具有相同的身份,它们也相等(在可互换的相等方面)。

回答by outis

Think about the words "identical" and "equivalent". If two things are identical, they have the same identity; they are same thing. If they are equivalent, one can be substituted for the other without affecting the outcome; they have the same behavior and properties.

想想“相同”和“等效”这两个词。如果两个事物相同,则它们具有相同的身份;他们是一回事。如果它们相等,可以用一个代替另一个而不影响结果;它们具有相同的行为和属性。

回答by u290629

For instance,

例如,

In StackOverFlow:

在 StackOverFlow 中:

  • identity: I am Michael, you are sevugarajan, so we are not same.

  • equality: if we have same reputation scores, we are equal in some ways.

  • 身份:我是迈克尔,你是sevugarajan,所以我们不一样。

  • 平等:如果我们有相同的声誉分数,我们在某些方面是平等的。