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...
I found very valuable information concerning this topic and many other topics in the Effective Java book, written by Joshua Bloch. Look at page 45 for further information about hashCode() and equals().
If you use an IDE like Eclipse you can let it generate the
hashCode()
andequals()
methods. For your class the result would be:similar to durron597's answer, you can try this if your input is bounded by char (between 0 and 65535 )
To implement hashCode, you override the default implementation from Object:
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-inArrays
class fromjava.util
(http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html):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:
Once you've done this, you can make compareTo take an argument of type
Coord
rather than typeObject
, which will save you the trouble of checking its type.Hashcode is an
int
(32 bits), your data ischar
(16 bits), so I would probably just do:This puts the bits from
row
in the first 16 bits and the bits fromcol
in the last 16 bits, so this is a perfect hash function for this class.If you refactor your class to be more complicated, I recommend using nullptr's answer.
To use
Comparable
, do: