Ich versuche, eine HashCode() -Methode für meine einfache Klasse zu generieren, aber ich komme nicht damit. Ich würde jede Hilfe schätzen. Ich habe die equals() -Methode implementiert, die wie folgt aussieht, und möchte auch wissen, ob ich die compareTo() -Methode implementieren muss. Ich habe java.lang.Character importiert, um character.hashCode() zu verwenden, aber es scheint nicht zu funktionieren.Wie schreibe ich HashCode-Methode für eine bestimmte Klasse?
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;
}
}
}
Vielen Dank im Voraus ...
Die comparto() -Methode, die mir java.lang.Comparable Gussfehler ..
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;
}
}
}
Dank schenkt ...
Ich denke, [Zwingende gleich und hashCode in Java] (http://stackoverflow.com/questions/27581/overriding-equals-and-hashcode-in-java?rq=1) wird Ihnen helfen. –