• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

about equals method?

 
vijay mahendra
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi one and all,

object1 and object2 are type of same object references

if object1.equals(object2) returns false

why its returning false value. i need reason behind that .

please any one give suggesions.

thanks
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It depends on the class definition. If a class definition doesn't override the equals(Object) method from Object.java, then it inherits the equals(Object) method from Object.java. That method simply tests whether the references refer to the same object.
 
Kaydell Leavitt
Ranch Hand
Posts: 689
Eclipse IDE Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
obj1 and obj2 may be referenced by the same type of object reference variable, but they might be different types of objects. If equals() was overriden properly, sometimes obj1 and obj2 are of different classes:

obj1.class() might not be equal to obj2.class()

Kaydell
 
Amit Ghorpade
Bartender
Posts: 2854
10
Fedora Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
the above posts describe exactly what is happening behind the scenes.
So the best way to check the equality of your custom objects is to override the .equals() method of the Object class and define the way in which you think that your objects/ object contents are equal.

Hope this helps
 
An Sush
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you open the class Object.java (inside src.zip of your jdk folder) which is superclass of all class, you will find the implementation of equals method and its like



So you can clearly see that the default implementation (in case you don�t define equals method in your class) is object reference equality and not value equality. If you want to have equals method work in your Object, you must override the implementation in your object.
You can refer what they have done in String.java


So based on what your object it and how you want to define your equality, you must override the method in your class

Hope it�s helpful
 
fred rosenberger
lowercase baba
Bartender
Pie
Posts: 12098
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Sushant",

You have apparently missed our Naming Policy on the way in. We require a real first name, followed by a space, and a last name. Please follow that link, read the page, and find the link there on how to correct your screen name. This policy is mandatory.

I would have contacted you privatly, but you did not register with an email.

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