Search a value for a given key in a HashMap

前端 未结 4 1161
余生分开走
余生分开走 2021-02-05 06:51

How do you search for a key in a HashMap? In this program, when the user enters a key the code should arrange to search the hashmap for the corresponding value and

4条回答
  •  醉酒成梦
    2021-02-05 07:30

    You wrote

    HashMap hashMap = new HashMap();
    ...
    int x = scan.nextInt();
    value = hashMap.get("x");
    

    must be:

    Map hashMap = new HashMap();
    ...
    int x = scan.nextInt();
    value = hashMap.get(x);
    

    EDIT or without generics, like said in the comments:

    int x = scan.nextInt();
    value = (String) hashMap.get(new Integer(x));
    

提交回复
热议问题