Alexander Simko Alexander Simko - 1 month ago 9
Java Question

Equality in java

The

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

Answer

== 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 a.foo() will have an effect on b.

Like:

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

System.out.println(b.getCounter());
a.foo();
System.out.println(b.getCounter());  

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.