java - 从 hashmap 打印出坐标

标签 java hashmap coordinates println

嗨,我有工作代码,但我想打印出坐标。有一个包含坐标和字符串的 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/

相关文章:

java - HashMap 说 Key 不存在,即使它存在

java - 收集可能为空的值

google-maps - 检查点是否在多边形( map )中

c# - 如何将框的边界转换为屏幕坐标

java - 通过 TCP 将图像路径 url 从本地 PC 发送到 Android 应用程序的最佳方式?

java - Spring-MVC 中的 JSP 渲染 HTML

java - 循环遍历包含字符串和另一个映射的映射

javascript - 如何返回文本输入中字符串末尾的绝对像素坐标?

java - 为图像编辑器快速、可靠地保存/加载文档状态

java - 当我将布局更改为不可见时如何修复 ClassNotFoundException