java - How to write hashCode method for a particular class? -
i'm trying generate hashcode() method simple class i'm not getting anywhere it. appreciate help. i've implemented equals() method, looks follows, , know if need implement compareto() method. i've imported java.lang.character use character.hashcode() doesn't seem 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 empty"); } else if(copy.getclass()!=this.getclass()){ throw new illegalargumentexception("object entered 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 giving me java.lang.comparable casting error..
public int compareto(object copy){ if(copy==null){ throw new nullpointerexception("object entered empty"); } else if(copy.getclass()!=this.getclass()){ throw new illegalargumentexception("object entered 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...
to implement hashcode, override default implementation object:
@override public int hashcode() { return row ^ col; }
this isn't ideal hash, since results predictable , easy 2 different coord
objects return same value. better hash make use of built-in arrays
class 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 method generate pretty hash number of fields.
to implement compareto, you'll want class implement comparable:
public class coord implements comparable<coord>
once you've done this, can make compareto take argument of type coord
rather type object
, save trouble of checking type.
Comments
Post a Comment