在HashMap中搜索给定键的值

bha*_*shi 18 java

你如何搜索一个关键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);  
    } 
} 
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 36

只需致电get:

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

String value = map.get("x"); // value = "y"
Run Code Online (Sandbox Code Playgroud)

  • 如果你想"搜索" - 即在检索之前检查可用性,你也可以使用containsKey方法.我不知道你需要那个,但问题就是这样说的.http://java.sun.com/j2se/1.4.2/docs/api/java/util/HashMap.html#containsKey%28java.lang.Object%29 (5认同)
  • 如果你忙着打败我们其他人的答案,你如何完成任何工作?您是否已经建立了一个用于过滤和回答SO问题的超级UI? (4认同)
  • 你是否在你的Hashmapdemo()类中的'hashmap'变量中放了一些东西来获取它()?为什么要返回'value',这是一个应该返回int的方法的字符串? (2认同)