2011-11-01 53 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)); 
    } 
}