我使用以下代码:
public void showTablet () {
for (Map.Entry<String, Tablet> entry : tableMap.entrySet()) {
System.out.println(entry.toString());
}
}
结果是:
MyBrand : A123=Brand: MyBrand, Model no.:A123, Price:3000.0
BrandTwo : T222=Brand: BrandTwo, Model no.:T222, Price:2500.0
我想要的结果
Brand: MyBrand, Model no.:A123, Price:3000.0
Brand: BrandTwo, Model no.:T222, Price:2500.0
为什么钥匙也打印出来了?
答案 0 :(得分:4)
因为您正在打印Map.Entry
,其中包含密钥和值。
如果您只想要该值,可以使用Map.Entry
的{{1}}方法:
getValue()
假设System.out.println(entry.getValue()); // will call toString by default
有一个正确覆盖的Tablet
方法,当然(如果我理解你的输出正确的话,它似乎有)。
答案 1 :(得分:3)
你不需要搞乱条目。
for(Tablet tablet : tabletMap.values()) {
System.out.println(tablet);
}
答案 2 :(得分:0)
尝试:
System.out.println(entry.getKey() + " : " + entry.getValue());
答案 3 :(得分:0)
以下是获取键/值对的示例...
public void showTablet () {
for (Map.Entry<String, Tablet> entry : tableMap.keySet()) {
System.out.println("Key: " + entry + " Value: " + tableMap.get(entry));
}
}