2012-08-02 106 views
0

嗨,我有工作代码,但我想打印出的坐标。有一个包含坐标和字符串的散列表。有一个坐标类允许我放置坐标,但是当我尝试打印时,它会让人感到困惑,我显然没有做正确的事情。感谢您的期待打印输出坐标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()); 
} 
} 
+0

你必须重载的toString你的坐标类 – Benoir 2012-08-02 19:37:00

回答

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

什么是混淆你是这样的:

[email protected] 

这是什么?这是原始toString()方法的结果。这里是做什么的:

return getClass().getName() + '@' + Integer.toHexString(hashCode()); 

所以,用自己的代码覆盖它会摆脱混乱输出的:)


请注意,有很大的哈希冲突的。一个更好的hashCode()的实现是:

public int hashCode() 
{ 
    return (x << 16)^y; 
} 

为了展示你的坏哈希码:一些冲突:

  • (0101)和(1,1)
  • (44120)和( 44012,0)
+0

IVE试过这个修复,但没有工作,它似乎不喜欢公共无效。然后当我尝试将其更改为公共字符串哈希映射不允许它 – Djchunky123 2012-08-05 16:02:30

+0

创建Hashmap时,我必须改变一些东西吗? – Djchunky123 2012-08-05 16:21:26

+0

不要担心意识到做什么我没有把它放在map.put函数,但把它放在println函数感谢您的帮助 – Djchunky123 2012-08-05 17:20:32

0

如马亭所述超越的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"); 

....

} 
+0

嗨,谢谢你的帮助,但你稍微离开,因为HashMap不会允许在打印函数中使用它的map.put函数中的tostring,而不是感谢帮助:) – Djchunky123 2012-08-05 17:22:21