【问题标题】:Checking variable value with hashmap data in java在java中使用hashmap数据检查变量值
【发布时间】:2016-10-13 18:03:16
【问题描述】:

我需要直接使用 hashmap 值检查我的变量值。

我的 hashmap 值在字符串中有两个条目,我需要使用 hashmap 的第一个条目检查我的变量值。

上面是小版本的代码。

HashMap<String , String> directory = new HashMap<String , String>();
    directory.put("AFG","Afghanistan");
    directory.put("GBR","United Kingdom of Great Britain and Northern Ireland");
    directory.put("IDN","Indonesia");
    directory.put("IND","India");

接下来我使用扫描器类来获取用户的值。然后我需要知道的是如何将此用户的值与哈希图的第一个条目(即 AFG、GBR 等)进行比较

整个程序的示例代码是:

import java.util.*;

public class hashmapdemo {
public static void main(String args[]) {

    HashMap<String , String> directory = new HashMap<String , String>();
    directory.put("AFG","Afghanistan");
    directory.put("GBR","United Kingdom of Great Britain and Northern Ireland");
    directory.put("IDN","Indonesia");
    directory.put("IND","India");

    Scanner sc = new Scanner(System.in);
    String name = sc.nextLine();
    System.out.println(name);

    // comparing logic ?

}
}

【问题讨论】:

  • 用户的输入是什么?键还是值?
  • hashmap 中没有顺序,如果顺序很重要,您应该查看其他数据结构。
  • 用户的输入将是关键部分,即 IND 等,我需要将其与 hashmap 值@Saravana 进行比较
  • 不,订单对我来说并不重要,我只想将该用户的输入与哈希图值进行比较@EduardoDennis
  • 您似乎混合了条目、键和值,这让您的问题难以理解

标签: java hashmap hashset


【解决方案1】:

首先,为了防止出现 nullPointer 异常,您需要确保您的 HashMap 包含用户输入键:

directory.containsKey(key)

如果成功,那么您可以返回相应键的值:

return directory.get(key);

String key = sc.nextLine();


       if(directory.containsKey(key))
       {
           return directory.get(key);
       }

【讨论】:

    【解决方案2】:

    你只需要

    directory.get(name);
    

    这将返回国家名称。

    为了避免NullPointerException:

    String countryName = directory.get(name);
    if (countryName != null) {
        // use your countryName variable
    }
    

    这比调用另一个不必要的方法(如directory.containsKey(name);)具有更好的性能

    【讨论】:

    • 我想是因为您需要在尝试直接访问之前检查地图是否包含密钥。
    • 如果键不存在,调用 directory.get(name) 将抛出 NullPointerException 程序将在检查值是否为空之前出错
    • @SamOrozco 请测试一下。它只是返回空值。它不会抛出任何异常。
    猜你喜欢
    • 2016-05-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-11
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-12
    相关资源
    最近更新 更多