开发者

What is the difference between identity and equality in OOP?

What is the difference 开发者_如何转开发between identity and equality in OOP (Object Oriented Programming)?


  • identity: a variable holds the same instance as another variable.

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

Identity

For example:

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

a is identical to b.

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

Equality

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

c is equal but not identical to d.

Of course, two identical variables are always equal.

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


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

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 ;-)


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)

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.


For instance,

In 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.


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.

There is also an equals method 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.

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.


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.


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

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

In theory it's possible to override a method equals() to return false even for identical objects. But this would break the specification of 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.


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).


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

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

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

i found an excellent article on this 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

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


x == y is true only if there's the same object referenced by variables x and 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();)

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


Identical vs. Equal objects

Two objects are said to have identical states (deep equality) if the graphs representing their states are identical in every respect, including the OIDs at every level.

Two objects are said to have equal states (shallow equality) if the graphs representing their states are same, including all the corresponding atomic values. However, some corresponding internal nodes in the two graphs may have objects with different OIDs. Example: This example illustrates the difference between the two definitions for comparing object states for equality.

o2 = (i 2 , tuple, <a 1 :i 5 , a 2 :i 6 >)
o3 = (i 3 , tuple, <a 1 :i 4 , a 2 :i 6 >)
o4 = (i 4 , atom, 10)
o5 = (i 5 , atom, 10)
o6 = (i 6 , atom, 20)

In this example, the objects o1 and o2 have equal states (shallow equality), since their states at the atomic level are the same but the values are reached through distinct objects o 4 and o 5 .

However, the objects o1 and o3 have identical states (deep equality), even though the objects themselves are not because they have distinct OIDs. Similarly, although the states of o4 and o5 are identical, the actual objects o4 and o5 are equal but not identical, because they have distinct OIDs.


To add, identity is also known as referential check (references to objects, get it?) and equality as structural check by some authors. At the end of the day an object in memory abstract is just a map/table structure indexed at certain memory address. There can be one or many references (memory addresses) pointing to it. They all are referential-ly identical. When contents of same object is copied to another counterpart then both are structurally equal.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜