2011-02-14 74 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还没有关联数组。但是,您可以使用哈希映射作为替代。