2013-04-26 30 views
0

我有2個班。如何打印出HashMap值?輸出像xxx @ da52a1

Main.java

import java.util.HashMap; 
import java.util.Map; 

public class Main { 
    Map<Integer, Row> rows = new HashMap<Integer, Row>(); 
    private Row col; 

    public Main() { 
     col = new Row(); 
     show(); 
    } 

    public void show() { 
     // col.setCol("one", "two", "three"); 
     // System.out.println(col.getCol()); 

     Row p = new Row("raz", "dwa", "trzy"); 
     Row pos = rows.put(1, p); 
     System.out.println(rows.get(1)); 

    } 

    public String toString() { 
     return "AA: " + rows; 
    } 

    public static void main(String[] args) { 
     new Main(); 
    } 
} 

和Row.java

public class Row { 

    private String col1; 
    private String col2; 
    private String col3; 

    public Row() { 
     col1 = ""; 
     col2 = ""; 
     col3 = ""; 
    } 

    public Row(String col1, String col2, String col3) { 
     this.col1 = col1; 
     this.col2 = col2; 
     this.col3 = col3; 
    } 

    public void setCol(String col1, String col2, String col3) { 
     this.col1 = col1; 
     this.col2 = col2; 
     this.col3 = col3; 
    } 

    public String getCol() { 
     return col1 + " " + col2 + " " + col3; 
    } 
} 

輸出總是看起來像 「行@ da52a1」 或類似。如何解決這個問題?我希望能夠做這樣的事,方便前往各字符串:

str="string1","string2","string3"; // it's kind of pseudocode ;) 
rows.put(1,str); 
rows.get(1); 

正如你所看到的,我創建的類行利用其作爲地圖的對象,但我不知道是什麼我的代碼有問題。

回答

2

覆蓋的toString方法您類是這樣的:

@Override 
public String toString() { 
    return col1 + " " + col2 + " " + col3; 
} 
+0

@Baadshah我有這個值,所以我認爲它運作良好。謝謝durron597 :) – tmq 2013-04-26 14:02:10

+0

@tmq沒問題,不要忘了點擊綠色的複選標記:) – durron597 2013-04-26 14:02:56

+0

@tmq這就是我給durron +1的原因:) – 2013-04-26 14:05:37

-1
return "AA: " + rows; its calling toString method on Row object 

實際上你必須要追加每列VAL

嘗試

return "AA: " +col1 + " " + col2 + " " + col3; //typo edited 
0

添加自定義toString方法到 cla SS。 toString是每個Java對象都有的方法。它存在這樣的情況。在Row類

0

覆蓋toString方法,並打印值要打印

你的情況,這種方法應該如下

@Override 
public String toString() { 
    return col1 + " " + col2 + " " + col3; 
} 
0

的System.out.println(行。得到(1));

rows.get(1)將返回對象類型。因此,當您將其打印到控制檯時,它將打印該對象。

要解決該問題,可以在返回String的Row類中實現並覆蓋toString()函數。

0

你得到行@ da52a1,因爲你最終調用字符串的默認toString方法,它結合了在16進制對象的哈希碼的類名。

通過創建您自己的toString方法,您可以告訴編譯器在您的對象上調用toString時顯示哪些值。

@Override 
public String toString() { 
    return this.col1 + " " + this.col2 + " " + this.col3; 
}