2011-02-14 73 views
6

我想知道如果在Java數組可以做這樣的事情:Java是否支持關聯數組?

int[] a = new int[10]; 
a["index0"] = 100; 
a["index1"] = 100; 

我知道我已經看到了在其他語言類似的功能,但我不是很熟悉的任何細節......只是,有辦法將值與字符串常量相關聯,而不僅僅是數字索引。有沒有辦法在Java中實現這樣的事情?

回答

2

你需要的是java.util.Map<Key, Value>接口和它的實現(例如HashMap)與String關鍵

+0

可能是`HashMap`。 – 2011-02-14 14:34:48

+0

@Jacob你的意思是`Hashtable` – 2011-02-14 14:35:22

+2

@FooBah呃,沒有。 – 2011-02-14 14:35:44

17

你不能用Java數組做到這一點。這聽起來像你想使用java.util.Map

Map<String, Integer> a = new HashMap<String, Integer>(); 

// put values into the map 
a.put("index0", 100); // autoboxed from int -> Integer 
a.put("index1", Integer.valueOf(200)); 

// retrieve values from the map 
int index0 = a.get("index0"); // 100 
int index1 = a.get("index1"); // 200 
0

您是否在尋找HashMap<k,v>()類?請點擊此處查看javadocs

粗略地說,用法是:

HashMap<String, int> a = new HashMap<String,int>(); 
a.put("index0", 100); 

0

java還沒有關聯數組。但是,您可以使用哈希映射作爲替代。