嗨即时通讯新的这个网站,需要帮助一个程序即时通讯工作。我的问题是我似乎不能存储字符串和两个整数(作为坐标)。我已经看过其他代码,但没有看到如何存储值。下面是我使用过的代码。代码似乎很好,但当试图存储的值我不能把多个整数。感谢您的时间商店X和Y坐标
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'值或非法强制转换。 – 2012-07-30 12:05:53
@MattiasBuelens我认为这个hashCode并不复杂,但与素数散列相比,更简单,对吗?它也有明显显示坐标的好处,以0分隔。 – 2017-02-27 14:22:46
@ K_7对于人来说,阅读可能并不复杂,但对于计算机来说,这绝对是比较复杂的(比如:更多的工作)。对于性能至关重要的代码,您希望'hashCode'尽可能少地做(尽管仍然给出一个体面的散列)。 OPs版本进行字符串连接和数字解析,而素数散列只是一个整数加法和一个整数乘法。 – 2017-02-28 20:46:16