2012-08-02 103 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