我使用以下代码:
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
为什么key也打印出来了?
最佳答案
因为您正在打印一个 Map.Entry
,其中包含键和值。
如果你只想要值,你可以使用Map.Entry
的getValue()
方法:
System.out.println(entry.getValue()); // will call toString by default
这是假设 Tablet
有一个正确覆盖的 toString
方法,当然(如果我正确理解你的输出,它似乎有)。
关于java - 在 Java 中使用 for 循环打印 TreeMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7962430/