Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

equals() method

 
Arun Maalik
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class first{
public static void main(String[] args){
first p=new first();
first q=new first();
if(p.equals(q))
System.out.println("Equals");
else
System.out.println("Not Equals");
}
}

Helo sir in the above code it is printing "Not Equals " why? also i would like to know that in which case equals function print "Equals" and in which case "Not Equals "

with Regard

Arun kumar maalik
 
Rusty Shackleford
Ranch Hand
Posts: 490
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check the API description of equals. They may be objects of the same type but they are two different objects in memory, so it is not symmetric. It fails in the definition of equivilence relation so is not equal.

Try this:


http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html

If you want different behavior you will need to override equals().
[ July 18, 2006: Message edited by: Rusty Shackleford ]
 
Arun Maalik
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks sir Thanks a lot for java Ranch
 
Campbell Ritchie
Sheriff
Pie
Posts: 49364
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
override equals().
. . . and don't forget to override hashCode() too.
 
ak pillai
author
Ranch Hand
Posts: 288
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
== is a shallow comparison, which only compares the identity.


The == returns true, if the variable reference points to the same object in memory. This is a �shallow comparison�.


equals() method is a deep comparison whick makes use of equals() method to make sure they are logically equal.

The equals() - returns the results of running the equals() method of a user supplied class, which compares the attribute values. The equals() method provides �deep comparison� by checking if two objects are logically equal as opposed to the shallow comparison provided by the operator ==.

If equals() method does not exist in a user supplied class then the inherited Object class's equals() method is run which evaluates if the references point to the same object in memory. The object.equals() works just like the "==" operator (i.e shallow comparison).

Overriding the Object class may seem simple but there are many ways to get it wrong, and consequence can be unpredictable behaviour.
[ July 18, 2006: Message edited by: ak pillai ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic