Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / January 2006

Tip: Looking for answers? Try searching our database.

Implementing the equals method

Thread view: 
Mike - 23 Dec 2005 00:41 GMT
I created an object SudokuXY. The objects can only be equal or not
equal, there is no concept of greater than or less than for these
objects. It is my understanding that if I want to compare one object to
another, I have to implement the equals method. Am I correct?

If so, is this a correct (valid) equals method?
        public boolean equals(SudokuXY e1)
        {
            System.out.println("Equals test for "+e1.toString()+
                              " in "+ this.toString());
            if (e1==null && this==null)
                return true;
            if (e1.x() == this.x() && e1.y()==this.y())
                return true;
            return false;
        }

Thanks
MikeB
Roedy Green - 23 Dec 2005 01:37 GMT
>If so, is this a correct (valid) equals method?
>        public boolean equals(SudokuXY e1)

no, not if you want to override the built-in object equals. It has a
signature like this public boolean equals( Object e1) to allow you to
compare any object not just another SudokuXY. Inside equals you can
check the type and if it is not a SudokuXY or subset thereof or ...
then return false.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Roedy Green - 23 Dec 2005 01:38 GMT
>if (e1==null && this==null)

that will never be true. instance methods can only be run on non-null
objects.

You can count on this != null being true always.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Dave Glasser - 23 Dec 2005 03:37 GMT
"Mike" <MPBrede@gmail.com> wrote on 22 Dec 2005 16:41:18 -0800 in
comp.lang.java.help:

>I created an object SudokuXY. The objects can only be equal or not
>equal, there is no concept of greater than or less than for these
[quoted text clipped - 3 lines]
>If so, is this a correct (valid) equals method?
>        public boolean equals(SudokuXY e1)

The method may work if only your code is calling it, but it won't be
the one called by Sets, Maps, Lists, etc., so you might not get the
behavior you're looking for. By making your argument of type SudokuXY
instead of Object, you didn't override Object.equals(), you overloaded
it.

You probably should make your argument an Object, and cast it to
SudokuXY inside the method.
Mike - 23 Dec 2005 05:31 GMT
So this is a better equals method?

public boolean equals(Object o)
{
    if (o instanceof SudokuXY)
    {
        SudokuXY e1 = (SudokuXY) o;
        System.out.println("Equals test for "+e1.toString()+
                          " in "+ this.toString());
        if ((e1.x() == this.x()) && (e1.y()==this.y()))
            return true;
    }
    return false;
}

I apologize if the lines are wrapping, but I'm having difficulty
pasting code - the tabs translate to much bigger spacing here than in
my editor. Can't figure it out.
Thomas Hawtin - 23 Dec 2005 10:21 GMT
> So this is a better equals method?
>
[quoted text clipped - 14 lines]
> pasting code - the tabs translate to much bigger spacing here than in
> my editor. Can't figure it out.

A more conventional way of writing it would be:

@Override // From 1.5
public boolean equals(Object obj) {
    if (!(obj instanceof SudokuXY)) {
        return false;
    }
    SudokuXY other = (SudokuXY)obj;
    return this.x == other.x && this.y == other.y;
}

The instanceof assumes that the class is final. Otherwise use something
like:

   if (obj == null || this.getClass() != other.getClass()) {
       return false;
   }

If you implement equals you should also implement hashCode:

@Override
public int hashCode() {
    return x + 37*y;
}

Tom Hawtin
Signature

Unemployed English Java programmer
http://jroller.com/page/tackline/

Mike - 23 Dec 2005 12:33 GMT
> > So this is a better equals method?
> >
[quoted text clipped - 39 lines]
>      return x + 37*y;
> }

Thank you, I'll work on fixing my method and adding the hashCode
method.

Is this
(http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Override.html) the
link to where the @Override is discussed? If not, could you please post
a link so I can read up on it?

Thanks
MikeB
Oliver Wong - 23 Dec 2005 18:29 GMT
> Is this
> (http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Override.html) the
> link to where the @Override is discussed? If not, could you please post
> a link so I can read up on it?

   This page does discuss @Override, but it's probably not the best way to
understand what @Override does. The '@' character shows that @Override is an
annotation, a feature that was only introduced in Java 1.5. So if you're not
using Java 1.5 or later, you can't use it.

   Even if you are using Java 1.5, it doesn't actually modify the behaviour
of your program. In that sense, it's sort of like a comment, but it's a
comment that the compiler can understand. It's a way of marking the method
as saying "I believe that I am override a method in the super class here",
and the compiler will notify you if it turns out that that belief is
incorrect.

   - Oliver
Roedy Green - 23 Dec 2005 13:15 GMT
>public boolean equals(Object o)
>{
[quoted text clipped - 8 lines]
>    return false;
>}

I would write it a bit more tersely like this:

public boolean equals( Object o )
 {
    if (! ( o instanceof SudokuXY) ) return false;
    SudokuXY s = (SudokuXY)o;
    return x() == s.x() && y() == s.y();
 }

I believe the ( before o instance of is necessary. Oddly, instanceof
has the same precedence as <.  I would have thought it should have had
the highest precedence.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Mike - 24 Dec 2005 01:01 GMT
Now that was a thrill. I wrote the method that deleted cell coordinates
in one list from another list and my equals method got used! Whoo!
Sorry, I just had to celebrate somewhere.

And PS. I can now solve 64 cells of a Sudoku puzzle that was too hard
for me to solve manually. Isn't progress great? LOL.
Roedy Green - 24 Dec 2005 01:07 GMT
>And PS. I can now solve 64 cells of a Sudoku puzzle that was too hard
>for me to solve manually. Isn't progress great? LOL.

Sounds like you are hooked now!.

The thing I have never understood it why people put so much effort
into solving artificial puzzles when there are so many real world
problems begging solution. See
http://mindprod.com/projects/projects.html
hint hint
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Mike - 24 Dec 2005 02:49 GMT
>  The thing I have never understood it why people put so much effort
> into solving artificial puzzles when there are so many real world
> problems begging solution. See
> http://mindprod.com/projects/projects.html
> hint hint

Hmm... this will take some thinking. You've almost succeeded in making
me feel guilty. ;)
I'll post back if I get a clear definition of why I chose a puzzle as a
project rather than any one of a myriad alternatives.

> --
> Canadian Mind Products, Roedy Green.
> http://mindprod.com Java custom programming, consulting and coaching.

Just FYI, based on your sig and on a Google ad that came up next to
your posting. Have you seen http://www.kasamba.com/ ?
ranganathkini@gmail.com - 30 Dec 2005 07:24 GMT
I wud write the equals() method like this:

public boolean equals( Object o ) {
   if( o == this )
       return true;
   if ( o instanceof SudokuXY ) {
       SudokuXY e1 = ( SudokuXY ) o;

       System.out.println( "Equals test for " + e1.toString() +
           " in " + this.toString() );

       // consider using the field references here instead of  x() and
y()
       if ( ( e1.x() == this.x() ) && ( e1.y() == this.y() ) )
           return true;
   }
   return false;
}
Oliver Wong - 09 Jan 2006 15:19 GMT
>I wud write the equals() method like this:
>
[quoted text clipped - 14 lines]
>    return false;
> }

   The problem with using "instanceof" as above is that "this" may actually
be a subclass of SudokuXY. For example, someone who wrote the above code
might also end up writing the following code:

<code>
class SudokuXYZ extends SudokuXY {
 private int z = 0;

 public void z(int newValue) {
   this.z = newValue;
 }

 public int z() {
   return z;
 }

 public boolean equals(Object o) {
   if (super.equals(o)) {
     if (other instanceof SudokuXYZ) {
       if (this.z == (SudokuXYZ).z) {
         return true;
       }
     }
   }
   return false;
 }
}
</code>

But now, imagine you have 3 objects:

<code>
SudokuXYZ s1, s2;
SudokuXY s3;

/*
[Assume the appropriate constructors are called so that:

s1.x = 100, s2.x = 100, s3.x = 100
s1.y = 200, s2.y = 200, s3.y = 200
s1.z = 400, s2.z = 800
*/
</code>

s3.equals(s1) will return true.
s3.equals(s2) will return true.
s1.equals(s2) will return false.

This breaks the contract of the equals() method which says that the equals
relationship should be transitive.

   - Oliver
iamfractal@hotmail.com - 30 Dec 2005 08:37 GMT
Notwithstanding all the excellent answers supplied so far (particularly
ranganathk...@gmail.com's), the excellent book, "Effective Java," shows
all the information you could ever want on overriding the equals()
method, and it just so happens that a sample chapter published on the
web covers this very topic; see Chapter 3:

http://java.sun.com/docs/books/effective/chapters.html

.ed

--
www.EdmundKirwan.com - Home of The Fractal Class Composition.


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.