这是我的方法。在哈希图中,我有一对欧洲的国家 - 首都(俄罗斯 - 莫斯科)。但是,它不断返回我的值(首都)而不是键(国家)。我测试了我的哈希图和它顺序正确。
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 ); }
我打印了我的国家。
任何想法为什么我的方法不能按预期工作?