tags:

views:

348

answers:

4

i switched lecturers today and he stated using a weird code too me.

he says its better. when i asked why, he asnwered "because it is!"

so much for that.

so heres an example:

if (o1.equals(o2))
{
  System.out.println("Both integer objects are the same");
}

instead of what im used too:

if (o1 == o2)
{
  System.out.println("Both integer objects are the same");
}

whats the difference between the two. and why is his way better?

found this but i cant really make sense of that answer http://www.javabeat.net/qna/13-what-is-difference-between-equals-and-/

+8  A: 

This has been asked many-a-time.

http://stackoverflow.com/questions/971954/difference-between-equals-and

Kezzer
guess searched the wrong place
OVERTONE
Since C# and Java don't act exactly the same way here, I think it's reasonable to have one question per language.
Joachim Sauer
It's a good thing the answer I referenced includes both Java _and_ C# then :)
Kezzer
+14  A: 

In Java, == always just compares two references (for non-primitives, that is) - i.e. it tests whether the two operands refer to the same object.

However, the equals method can be overridden - so two distinct objects can still be equal.

For example:

String x = "hello";
String y = new String(new char[] { 'h', 'e', 'l', 'l', 'o' });

System.out.println(x == y); // false
System.out.println(x.equals(y)); // true
Jon Skeet
+1  A: 

The == operator compares if the objects are the same instance. The equals() oerator compares the state of the objects (e.g. if all attributes are equal). You can even override the equals() method to define yourself when an object is equal to another.

Sylar
Note that the default implementation of `equals()` in `Object` falls back to effectively `this == other`. That's a common source of confusion, since you won't see a difference unless you're using a class that actually implement `equals()` in a meaningful way.
Joachim Sauer
Right, I should have mentioned that. The questioner can look at the JDK itself, there are numerous classes he can take as example.
Sylar
A: 

If you and I each walk into the bank, each open a brand new account, and each deposit $100, then...

  1. myAccount.equals(yourAccount) is true because they have the same value, but
  2. myAccount == yourAccount is false because they are not the same account.

(Assuming appropriate definitions of the Account class, of course. ;-)

joel.neely
That would be a really really bad implementation of equals.
It was also a really, really bad explanation of the difference between == and equals.
jarnbjo