Alexander Simko Alexander Simko - 4 months ago 27
Java Question

Equality in java


operator in java checks if two objects are at the same memory location. Dose this mean that if
object1 != object2
is not linked with
? By linked I mean that if
is changed then
is also changed.


== checks if two references are identical.

In other words: if that check returns true, there is only one object.

If it returns false, there are two objects.

But of course, one can easily write some code where a != b; but will have an effect on b.


class Bar {
  private static int counter = 0;
  void foo() { counter++ };
  int getCounter() { return counter; }

When you now have:

Bar a = new Bar();
Bar b = new Bar();

then a != b; but still, when you do


will print 0 and then 1.

So in essence, the answer to your second question is: a != b does not imply that "doing something with a" does nothing to b".

But for the record - that last sentence is the reason why static can be seen as abnormality in good OO design; exactly for such "strange" side effects.

Edit to answer on "what happens with containers and clone"?

Of course, when you have something like:

List<WhatEver> a = some list containing one object "X"
List<WhatEver> b = a "clone" of a

Then a != b; but of course; when you call a.get(0).foo() that affects b.get(0) ... because both lists internally point to the same X

And you see: in that case, a.equals(b) would return true; whereas a == b is false.