嗨,我有工作代码,但我想打印出坐标。有一个包含坐标和字符串的 HashMap 。有一个坐标类可以让我输入坐标,但是当我尝试打印出来时,它会感到困惑,我显然没有做正确的事情。感谢您的浏览
public class XYTest {
static 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, String> map = new HashMap<Coords, String>();
map.put(new Coords(65, 72), "Dan");
map.put(new Coords(68, 78), "Amn");
map.put(new Coords(675, 89), "Ann");
System.out.println(map.size());
}
}
最佳答案
您必须在 Coords 类中重写 toString()
。
static 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 String toString()
{
return x + ";" + y;
}
}
让你感到困惑的是这样的:
XYTest.Coords@3e25a5
这是什么?它是原始 toString()
方法的结果。它的作用如下:
return getClass().getName() + '@' + Integer.toHexString(hashCode());
因此,用您自己的代码覆盖它将消除令人困惑的输出:)
<小时/>请注意,您有很大的哈希冲突。更好的 hashCode() 实现是:
public int hashCode()
{
return (x << 16) ^ y;
}
为了演示您的错误哈希代码:一些冲突:
- (0,101)和(1,1)
- (44,120)和(44012,0)
关于java - 从 hashmap 打印出坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11784570/