【问题标题】:Hashmap keySet() returns the value instead of the keyHashmap keySet() 返回值而不是键
【发布时间】:2016-02-05 00:45:51
【问题描述】:

这是我的方法。在哈希图中,我有一对欧洲的国家 - 首都(俄罗斯 - 莫斯科)。但是,它不断返回值(首都)而不是键(国家)。我测试了我的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);...既然您已经转换为字符串,为什么不将结果存储在字符串而不是对象中,这需要再次转换?...跨度>
  • String theKeyValue = (String) theMap.get(randomKey); return theKeyValue;

标签: java hashmap keyset


【解决方案1】:

您在此处获取值:

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

如果您希望randomCountry 返回密钥,则应返回randomKey 而不是theKeyValue。

【讨论】:

    【解决方案2】:
    Object theKeyValue = (String )theMap.get(randomKey);
    

    你可以返回randomKey。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-31
      • 2021-08-03
      • 1970-01-01
      • 2018-02-23
      • 1970-01-01
      • 1970-01-01
      • 2020-08-07
      • 2019-08-12
      相关资源
      最近更新 更多