Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

a doubt in equals() method

 
rajaraman navaneethan
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello friends,
thanx very much for your previous responses for my doubt in exception hadling.plz clear me of this doubt about equals() method.

question:

class a
{
a(int x)
{
System.out.println(x);
}
}

class b
{
public static void main(String args[])
{
a ob1=new a(100);
a ob2=new a(100);

System.out.println(ob1.equals(ob2));
}
}


the output of this is false,even though both ob1 and ob2 are objects of class a and the value passed to the constructor is also same.i thought that .equals() method checks the contents of the object and returns a boolean value.
please clear me of this doubt as how .equal() works,
regards,
raja
 
Horatio Westock
Ranch Hand
Posts: 221
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The default equals method (supplied by java.lang.Object) actually uses ==

If you want to use equals for your own classes, you have to override public boolean equals(Object o), and make it do something sensible for your type.

this might be interesting
 
Subbarao Anaparthi
Greenhorn
Posts: 2
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
equals() on Object(Except for String & Wrapper Classes) uses == operator.

for example
Object o=new Object();
Object o1=o;
if(o1.equals(o)) returns true becaus o,o1 references points to same object.
equals() is overridden into String & Wrapper Classes.
and equals() in String and All Wrapper classes compares the contents in the reference variable.

thats why equals() works differently on String & StringBuffer.
because equals() on StringBuffer takes equals() from Object and equals() on String takes the overridden method in String class.

[ March 01, 2005: Message edited by: Subbarao Anaparthi ]
[ March 01, 2005: Message edited by: Subbarao Anaparthi ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic