如何为特定类编写hashCode方法? [英] How to write hashCode method for a particular class?
问题描述
我正在尝试为我的简单类生成一个hashCode()方法,但我没有得到它的任何地方。我将不胜感激任何帮助。我已经实现了equals()方法,如下所示,并且还想知道我是否需要实现compareTo()方法。我已经导入了java.lang.Character来使用character.hashCode()但它似乎不起作用。
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;
}
}
}
谢谢提前...
给我java.lang.Comparable转换错误的comparTo()方法..
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;
}
}
}
谢谢......
推荐答案
要实现hashCode,请覆盖Object的默认实现:
To implement hashCode, you override the default implementation from Object:
@Override
public int hashCode()
{
return row ^ col;
}
这不是一个理想的哈希,因为它的结果是非常可预测的两个不同的 Coord
对象很容易返回相同的值。更好的哈希将使用 java.util
中的内置 Arrays
类( http://docs.oracle.com/javase/7/docs/api/java/util/Arrays。 html ):
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.
要实现compareTo,你需要你的类实现 Comparable :
To implement compareTo, you'll want your class to implement Comparable:
public class Coord implements Comparable<Coord>
完成此操作后,您可以使compareTo采用 Coord
而不是输入 Object
,这将为您省去检查其类型的麻烦。
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.
这篇关于如何为特定类编写hashCode方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!