-1

这是我的方法。在哈希图中,我有一对欧洲的国家 - 首都(俄罗斯 - 莫斯科)。但是,它不断返回我的值(首都)而不是键(国家)。我测试了我的哈希图和它顺序正确。

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 ); }

我打印了我的国家。

任何想法为什么我的方法不能按预期工作?

4

2 回答 2

2

您正在此处获取值:

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

如果要randomCountry返回密钥,则应返回randomKey而不是theKeyValue.

于 2015-11-04T13:36:07.153 回答
0
Object theKeyValue = (String )theMap.get(randomKey);

你可以返回随机密钥。

有关 keySet() 的更多详细信息,请查找 HashMap 文档链接:仅返回 Key 和 entrySet() :返回键值对。

https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html

于 2015-11-04T14:01:28.327 回答