2011-11-01 51 views
1

我用下面的代码循环:打印使用TreeMap的一个在Java

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 

为什么是关键还打印出来了?

回答

4

因为您正在打印一个Map.Entry,它包含键和值。

如果你只想要的值,你可以使用Map.EntrygetValue()方法:

System.out.println(entry.getValue()); // will call toString by default 

这是假设Tablet有一个正确重写toString方法,当然,(它似乎有,如果我正确理解你的输出)。

+2

或者只是通过['Map.values()'](http://download.oracle.com/迭代javase/7/docs/api/java/util/Map.html#values())并跳过所有条目。 –

0

尝试:

System.out.println(entry.getKey() + " : " + entry.getValue()); 
3

你并不需要的Entry混乱。

for(Tablet tablet : tabletMap.values()) { 
    System.out.println(tablet); 
} 
0

这里得到键/值对的例子...

public void showTablet() { 
    for (Map.Entry<String, Tablet> entry : tableMap.keySet()) {  
     System.out.println("Key: " + entry + " Value: " + tableMap.get(entry)); 
    } 
}