2010-06-16 86 views
15

如何在HashMap中搜索密鑰?在這個程序中,當用戶輸入一個密鑰時,代碼應該安排在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); 
    } 
} 
+3

製作務必通過點擊旁邊的「打勾」來接受回答您的問題的答案。 – 2010-06-16 07:56:29

回答

30

只需撥打get

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

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

你如何完成任何工作Jon如果你忙着毆打我們其他人的答案?你有沒有建立一個超級用戶界面來過濾和回答這些問題? – 2010-06-16 07:55:35

+4

如果您想「搜索」 - 即在檢索之前檢查可用性,您也可以使用containsKey方法。我不知道你需要這個,但問題是這樣說的。 http://java.sun.com/j2se/1.4.2/docs/api/java/util/HashMap.html#containsKey%28java.lang.Object%29 – 2010-06-16 07:55:54

+1

@Graphain:我沒有做正確的工作現在 - 我正在聽NDC的Chris Sells :) – 2010-06-16 07:57:50

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

它仍然給erroe說:cast ... get(...)到字符串 – 2010-06-16 09:33:09

+0

這裏value是一個字符串變量 – 2010-06-16 09:33:39

+1

get方法返回一個對象。你必須像下面這樣將它轉換爲一個字符串:value =(String)hashMap。get(new Integer(x));或者你使用所謂的「泛型」來告訴編譯器在你的映射中只有字符串,就像我在我的例子中使用「」 – 2010-06-16 09:37:16

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