How to write hashCode method for a particular class?

A Gore picture A Gore · May 4, 2013 · Viewed 18k times · Source

I'm trying to generate a hashCode() method for my simple class but i'm not getting anywhere with it. I would appreciate any help. I've implemented the equals() method, which looks as follows, and would also like to know if I need to implement compareTo() method. I've imported java.lang.Character to use character.hashCode() but it doesn't seem to work.

private class Coord{
    private char row;
    private char col;
    public Coord(char x, char y){
        row = x;
        col = y;
    }
    public Coord(){};

    public char getX(){
        return row;
    }

    public char getY(){
        return col;
    }

    public boolean equals(Object copy){
        if(copy == null){
            throw new NullPointerException("Object entered is empty");
        }
        else if(copy.getClass()!=this.getClass()){
            throw new IllegalArgumentException("Object entered is not Coord");
        }
        else{
            Coord copy2 = (Coord)copy;
            if(copy2.row==this.row && copy2.col==this.col)
                return true;
            else
                return false;
        }
    }

}

Thanks in advance...

The comparTo() method that is giving me java.lang.Comparable casting error..

public int compareTo(Object copy){
        if(copy==null){
            throw new NullPointerException("Object entered is empty");
        }
        else if(copy.getClass()!=this.getClass()){
            throw new IllegalArgumentException("Object entered is not Coord");
        }
        else{
            Coord copy2 = (Coord)copy;
            if(copy2.row==this.row && copy2.col==this.col){
                return 0;
            }
            else if(copy2.col < this.col){
                return -1;
            }
            else{
                return 1;
            }
        }
    }

thanks...

Answer

nullptr picture nullptr · May 4, 2013

To implement hashCode, you override the default implementation from Object:

@Override
public int hashCode()
{
    return row ^ col;
}

This isn't really an ideal hash, since its results are very predictable and it is easy for two different Coord objects to return the same value. A better hash would make use of the built-in Arrays class from java.util (http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html):

@Override
public int hashCode()
{
    return Arrays.hashCode(new Object[]{new Character(row), new Character(col)});
}

You can use this method to generate a pretty good hash with any number of fields.

To implement compareTo, you'll want your class to implement Comparable:

public class Coord implements Comparable<Coord>

Once you've done this, you can make compareTo take an argument of type Coord rather than type Object, which will save you the trouble of checking its type.