java如何打印HashMap值?输出像xxx@da52a1
我有两门课
梅因。爪哇
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();
}
}
还有划船。爪哇
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;
}
}
输出总是看起来像“Row@da52a1“或类似的。如何解决这个问题?我希望能够轻松访问每个字符串:
str="string1","string2","string3"; // it's kind of pseudocode ;)
rows.put(1,str);
rows.get(1);
如您所见,我创建了类行以将其用作Map的对象,但我不知道我的代码出了什么问题
# 1 楼答案
向
Row
类添加一个自定义toString
方法toString
是每个Java对象都拥有的方法。在这种情况下它是存在的# 2 楼答案
你越来越坚强了Row@da52a1,因为您最终调用了字符串的默认
toString
方法,该方法以十六进制表示法将对象的类名与哈希代码结合起来通过创建自己的
toString
方法,可以告诉编译器在对对象调用toString
时要显示哪些值