2015-11-04 64 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! –

相关问题