这是我的方法。在hashmap中,我有两对欧洲的Country-Capital(Russia-Moscow)。然而,它不断向我返回值(首都),而不是密钥(国家)。我测试了我的hashmap,它的顺序是正确的。
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 ); }
我把我的国家印出来。
有什么想法为什么我的方法没有按预期工作吗?
您在这里获取值:
Object theKeyValue = (String )theMap.get(randomKey);
如果希望randomCountry
返回密钥,则应返回randomKey
而不是theKeyValue
。
Object theKeyValue = (String )theMap.get(randomKey);
您可以返回randomKey。
有关keySet():仅返回Key和entrySet():返回键值对的更多详细信息,请参阅HashMap文档链接。
https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html