在HashMap中搜索给定键的值

时间:2010-06-16 07:48:56

标签: java

如何搜索HashMap中的密钥?在此程序中,当用户输入密钥时,代码应安排在hashmap中搜索相应的值,然后将其打印出来。

请告诉我为什么它不起作用。

import java.util.HashMap;

import java.util.; import java.lang.;

public class Hashmapdemo  
{
    public static void main(String args[]) 
    { 
        String value; 
        HashMap hashMap = new HashMap(); 
        hashMap.put( new Integer(1),"January" ); 
        hashMap.put( new Integer(2) ,"February" ); 
        hashMap.put( new Integer(3) ,"March" ); 
        hashMap.put( new Integer(4) ,"April" ); 
        hashMap.put( new Integer(5) ,"May" ); 
        hashMap.put( new Integer(6) ,"June" ); 
        hashMap.put( new Integer(7) ,"July" );  
        hashMap.put( new Integer(8),"August" );  
        hashMap.put( new Integer(9) ,"September");  
        hashMap.put( new Integer(10),"October" );  
        hashMap.put( new Integer(11),"November" );  
        hashMap.put( new Integer(12),"December" );

        Scanner scan = new Scanner(System.in);  
        System.out.println("Enter an integer :");  
        int x = scan.nextInt();  
        value = hashMap.get("x");  
        System.out.println("Value is:" + value);  
    } 
} 

4 个答案:

答案 0 :(得分:35)

只需致电get

HashMap<String, String> map = new HashMap<String, String>();
map.put("x", "y");

String value = map.get("x"); // value = "y"

答案 1 :(得分:2)

你写了

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

必须是:

Map<Integer, String> hashMap = new HashMap<Integer, String>();
...
int x = scan.nextInt();
value = hashMap.get(x);

编辑或没有泛型,如评论中所述:

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

答案 2 :(得分:1)

要对hashMap进行贴花,请使用以下代码:

 HashMap<Integer,String> hm=new HashMap<Integer,String>();

要在HashMap中输入元素,

 hm.put(1,"January");
 hm.put(2,"Febuary");

在搜索元素之前,首先使用方法containsKey()来检查哈希映射中是否存在输入数字,该方法将返回布尔值:

 if(hm.containsKey(num))
 {
    hm.get(num);
 }

答案 3 :(得分:0)

//如果你想要键是整数,那么你必须声明hashmap //如下:

HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(0, "x");
map.put(1, "y");
map.put(2, "z");

//输入整数值x

String value = map.get(x);