Friday, May 16, 2014

What is the difference between identity and equality in OOP?

basically,
  • identity -> a variable holds the SAME instance as another variable.
  • equality -> two (distinct) objects can be used interchangeably. they often have the same id.
for example
Integer a =  new Integer(1);
Integer b = new Integer(1);
a is equal but not identical to b.
Integer x = new Integer(1);
Integer y = x;
x is identical to y.
of course, two identical objects are always equal.
in java, equality is defined by the equals method. keep in mind, if you implement equals you must also implementhashCode.

No comments:

Post a Comment