简体   繁体   English

在 HashMap 中搜索给定键的值

[英]Search a value for a given key in a HashMap

How do you search for a key in a HashMap ?如何在HashMap搜索键? In this program, when the user enters a key the code should arrange to search the hashmap for the corresponding value and then print it.在这个程序中,当用户输入一个键时,代码应该安排在 hashmap 中搜索相应的值,然后打印出来。

Please tell me why it's not working.请告诉我为什么它不起作用。

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);  
    } 
} 

Just call get :只需调用get

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

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

You wrote你写了

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

must be:必须是:

Map<Integer, String> hashMap = new HashMap<Integer, String>();
...
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));

To decalare the hashMap use this:要 decalare hashMap 使用这个:

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

To enter the elements in the HashMap:要在 HashMap 中输入元素:

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

before searching element first check that the enter number is present in the hashMap for this use the method containsKey() which will return a Boolean value:在搜索元素之前,首先检查输入数字是否存在于 hashMap 中,为此使用方法 containsKey() 将返回一个布尔值:

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

//If you want the key to be integer then you will have to declare the hashmap //as below : //如果您希望键为整数,则必须声明哈希映射 //如下:

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

//input a integer value x //输入一个整数值x

String value = map.get(x);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM