Tôi đang cố gắng để tạo ra một phương thức hashCode() cho lớp đơn giản của tôi nhưng tôi không nhận được bất cứ nơi nào với nó. Tôi sẽ đánh giá cao sự giúp đỡ nào. Tôi đã thực hiện phương thức equals(), trông giống như sau, và cũng muốn biết nếu tôi cần phải thực hiện phương thức compareTo(). Tôi đã nhập java.lang.Character để sử dụng character.hashCode() nhưng nó dường như không hoạt động.Làm thế nào để viết phương thức hashCode cho một lớp cụ thể?
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;
}
}
}
Cảm ơn trước ...
Các comparTo() phương pháp đó là đem lại cho tôi lỗi đúc java.lang.Comparable ..
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;
}
}
}
nhờ ...
Tôi nghĩ [Overriding equals và hashCode trong Java] (http://stackoverflow.com/questions/27581/overriding-equals-and-hashcode-in-java?rq=1) sẽ giúp bạn. –