大家好,我是这个网站的新手,需要帮助解决我正在开发的一个程序的问题。我遇到的问题是似乎无法存储字符串和两个整数(作为坐标)。我查看了其他代码,但不知道如何存储值。下面是我一直在使用的代码。代码看起来没问题,但当我尝试存储这些值时,我无法同时输入多个整数。谢谢你们的时间。
import java.util.HashMap;
public class map {
class Coords {
int x;
int y;
public boolean equals(Object o) {
Coords c = (Coords) o;
return c.x == x && c.y == y;
}
public Coords(int x, int y) {
super();
this.x = x;
this.y = y;
}
public int hashCode() {
return new Integer(x + "0" + y);
}
}
public static void main(String args[]) {
HashMap<Coords, Character> map = new HashMap<Coords, Character>();
map.put(new coords(65, 72), "Dan");
}
}
x + (某个质数) * y
,例如x + 31*y
?另外,请注意您的equals
实现没有考虑到null
值或非法转换。 - Mattias BuelenshashCode
尽可能少地执行操作(同时仍然提供合理的哈希值)。原帖中的版本执行了字符串连接和数字解析,而质数哈希只需要一个整数加法和一个整数乘法。 - Mattias Buelens