0

I have 2 classes.

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

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

Output always looks like "Row@da52a1" or similar. How to fix that? I want to be able to do something like this with easy access to each of strings:

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

As you can see, I've created class Row to use its as object of Map, but I have no idea what is wrong with my code.

4

6 回答 6

2

像这样覆盖你的类的toString方法:Row

@Override
public String toString() {
    return col1 + " " + col2 + " " + col3;
}
于 2013-04-26T13:57:34.983 回答
0

您将获得Row@da52a1,因为您最终调用了String 的默认toString方法,该方法将类名与对象的哈希码以十六进制表示法结合在一起。

通过创建自己的方法,您可以告诉编译器在调用对象toString时要显示哪些值。toString

@Override
public String toString() {
    return this.col1 + " " + this.col2 + " " + this.col3;
}
于 2013-04-26T14:07:42.863 回答
0

覆盖 Row 类中的 toString 方法,并打印要打印的值

在您的情况下,此方法应如下所示,

@Override
public String toString() {
    return col1 + " " + col2 + " " + col3;
}
于 2013-04-26T13:59:47.037 回答
0

向类添加自定义toString方法RowtoString是每个 Java 对象都有的方法。它存在于这样的情况。

于 2013-04-26T13:57:40.770 回答
0

System.out.println(rows.get(1));

rows.get(1)将返回 Object 类型Row。因此,当您将其打印到控制台时,它将打印该对象。

要解决此问题,您可以在返回 String 的 Row 类中实现和覆盖toString()函数。

于 2013-04-26T14:01:43.843 回答
-1
return "AA: " + rows;   its calling toString method on Row object 

实际上你必须附加每一列 val

尝试

return "AA: " +col1 + " " + col2 + " " + col3;  //typo edited
于 2013-04-26T13:57:06.637 回答