GeeCON Prague 2014*
The moose likes Java in General and the fly likes Equals  method. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "Equals  method." Watch "Equals  method." New topic
Author

Equals method.

Mubeen Shaik
Ranch Hand

Joined: Jan 26, 2004
Posts: 67
Hi All,

I am not understandng thic concept. Why it is giving "False" as result.
This code is from Thinking in Java.

In the same code if i remove static from this code it is giving me error message. Please explain this concept also.

static Test monitor = new Test();





Thanks in advance,
Mubeen Shaik.


Sun Certified Java Programmer
Mubeen Shaik
Ranch Hand

Joined: Jan 26, 2004
Posts: 67
Hi,

I think i have posted this in wrong place. Could you please move this to Java Intemediate forum.


Thanks,
Mubeen Shaik.
Tim McGuire
Ranch Hand

Joined: Apr 30, 2003
Posts: 820

As the book says, the default behavior of the equals() method is to compare references. v1 and v2 are referencing different objects.

equals is inherited from Object and if you want to tell the method to compare values, then you have to override (write your own method of the same name with the same arguments) with something like:

[ May 19, 2004: Message edited by: Tim McGuire ]
John Smith
Ranch Hand

Joined: Oct 08, 2001
Posts: 2937
public boolean equals(Value v){

A small but important correction: the signature of the equals() method is public boolean equals(Object o). In the form quoted above, the equals() method is overloaded, not overriden. As a result, you will see some strange effects. For example:

Tim McGuire
Ranch Hand

Joined: Apr 30, 2003
Posts: 820

ooops!
thanks for pointing that out.
Mubeen Shaik
Ranch Hand

Joined: Jan 26, 2004
Posts: 67
Hi Eugene,

I am confused here, then how to Override the method?

Thanks,
Mubeen Shaik.
Stefan Wagner
Ranch Hand

Joined: Jun 02, 2003
Posts: 1923

overload:

overwrite:


http://home.arcor.de/hirnstrom/bewerbung
John Smith
Ranch Hand

Joined: Oct 08, 2001
Posts: 2937
Or simply
Manish Hatwalne
Ranch Hand

Joined: Sep 22, 2001
Posts: 2578

And don't forget to override hashcode method if you override equals.

- Manish
Tim McGuire
Ranch Hand

Joined: Apr 30, 2003
Posts: 820

So, getting equals() right and overriding the hashCode() method could look like this?:

John Smith
Ranch Hand

Joined: Oct 08, 2001
Posts: 2937
Tim -- yes, that looks better. The hashCode() method could be simplified, though:



Also, a better test would be:


There is much more to equals() and hashCode(). The best reference on this subject (and many others) is Effective Java
[ May 21, 2004: Message edited by: Eugene Kononov ]
 
GeeCON Prague 2014
 
subject: Equals method.