• Post Reply Bookmark Topic Watch Topic
  • New Topic

Which is more efficient? "==" or "Object.equals()"

 
Esmaeil Ashrafi
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi;
I'm interested in this matter for same circumstances (ignore Strings....)

Thanks in advance
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
These are NOT THE SAME. Back to basics.

The == operator tests for identity of reference (objects) or value (primitives).

The equals() method call tests for identity of content and should be implemented separately for each class.

Here is your assignment - get the source code for the standard library and look at the implementation of equals() for java.lang.Object and an assortment of other classes.

Bill
 
Esmaeil Ashrafi
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Bill,i think you made the subject more clear to me, specially this:
The == operator tests for identity of reference (objects) or value (primitives).

Actually i know every class could (and should if interested) override the method , but the default behaviour that implemented in class Object, looked similar to the operator "==" to me
Also this one:
The equals() method call tests for identity of content

helped a lot

I think the same affect for String objects (in most cases) caused me toi such a assumption...

Thanks.
 
Elchin Asgarli
Ranch Hand
Posts: 222
Chrome Eclipse IDE Google Web Toolkit
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Esmaeil Ashrafi wrote:
I think the same affect for String objects (in most cases) caused me toi such a assumption...


The effect for String objects in most cases are same, because Strings are internally cached by JVM (one of the reasons from the to be immutable). But for your applications, never depends on this, because it is not guaranteed behavior from JVM, so with String always use .equals()

You will also observe the same for Boolean, Byte, Character from \u0000 to \u007f (127), Short and Integer from -128 to 127, this is because these objects are also cached and are immutable.
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well of course the java.lang.Object class uses == for equals, thats the only possible definition since Object contains no variables.



Thats the reason I suggested you look at it.

Bill
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!