2015-11-04 62 views
-1

這裏是我的方法。在哈希映射中,我有一對國家 - 首都(俄羅斯 - 莫斯科)歐洲。但是,它不斷返回我的價值的關鍵(國家)。我測試了我的hashmap,它的順序是正確的。Hashmap keySet()返回值而不是密鑰

Map<String, String> europe1 = new HashMap<String, String>() 

public String randomCountry(Map theMap) 
{ 
    Random generator = new Random(); 
    List<String> keys = new ArrayList<String>(theMap.keySet()); 
    String randomKey = keys.get(generator.nextInt(keys.size())); 
    Object theKeyValue = (String)theMap.get(randomKey); 

    System.out.println(theKeyValue); 
    return (String) theKeyValue; 
} 

如果我這樣做:

for (String key : europe1.keySet()) 
{ System.out.println(key); } 

我讓我的國家印刷。

任何想法爲什麼我的方法不能按預期工作?

+0

'對象theKeyValue =(字符串)theMap.get(隨機key);'...因爲你已經轉換爲String,你爲什麼不只是結果存儲在一個字符串,而不是對象,這需要另一個演員?... – Tgsmith61591

+0

'String theKeyValue =(String)theMap.get(randomKey);' \t 'return theKeyValue;' –

回答

2

您在這裏取的值:

Object theKeyValue = (String)theMap.get(randomKey); 

如果你想randomCountry返回鍵,你應該返回randomKey,而不是theKeyValue

+0

Ups .. right.Thanks! –

相關問題