Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Difference in equals() method and comparision operator

 
Vishnu Sharma
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am not clear exactly about the equals() method of Object class and '==' operator and overlaoded equals() method and '==' operator
 
Campbell Ritchie
Sheriff
Pie
Posts: 48964
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Object#equals(java.lang.Object) method looks something like this:Overloading the equals method is almost always a serious mistake.
You can override the equals method to take any sort of comparison you like. It is often necessary to override equals, but look in books like Bloch or google for Angelika Langer Java equals where you will find how careful you must be about it.
 
Brian Campbell
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not completely sure if this is the question you're asking, but it might be worth pointing out that when you compare two objects using the == operator, you are testing whether the two values refer to the same object. As Campbell pointed out, the "default" equals() method in the Object class does the same thing.

On the other hand, String and most other Java core classes define the equals() method so that it compares the actual values of objects. If you want equals() to do this for your user-defined classes, you have to override the equals() method in Object. As Campbell mentioned, getting that override correct might not be a trivial task.
 
Campbell Ritchie
Sheriff
Pie
Posts: 48964
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch, BC
 
Brian Campbell
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:Welcome to the Ranch, BC


Thanks!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic