Java 在 HashMap 中搜索给定键的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3051486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:00:32  来源:igfitidea点击:

Search a value for a given key in a HashMap

java

提问by bhavna raghuvanshi

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 then print it.

你如何在 a 中搜索一个键HashMap?在这个程序中,当用户输入一个键时,代码应该安排在 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);  
    } 
} 

采纳答案by Jon Skeet

Just call get:

只需致电get

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

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

回答by Tim Büthe

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

回答by Gagan Prajapati

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