2013-04-26 32 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; 
}