print out hashmap中的坐标

时间:2012-08-02 19:35:06

标签: java hashmap coordinates println

嗨我有工作代码,但我想打印出坐标。有一个包含坐标和字符串的散列图。有一个坐标的课程允许我放入坐标,但是当我尝试打印时,它会让我感到困惑,显然没有做正确的事情。谢谢你看

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());
}
}

2 个答案:

答案 0 :(得分:3)

您必须在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)

答案 1 :(得分:0)

正如Martijn所说的覆盖toString()

class Coords {
....

public String toString(){
   return this.x + "-" + this.y;
 }
....

}

...和

  public static void main(String []args){

...

    map.put(new Coords(65, 72).toString(), "Dan");

...

  }