2013-04-26 103 views
3

我是Java的新手,所以我對它沒有太多的瞭解。當我在Java中發現真正令人沮喪的事情時,我正在與Array一起工作。使用字符串作爲JAVA中多維數組的索引

我有一個字符串數組,我想索引是一個字符串。例如

String[][] a = new String[][]{}; 
a['person']['name'] = "something"; 

但Java不讓我這樣做。請幫助我解決這個問題或者一些解決方法。 感謝

+0

你不能用'array'或'arrayList'做到這一點。看看'HashTable'(或'HashMap')類。 – 2013-04-26 02:59:20

+0

我認爲你可以使用'hashCode()'返回一個整數值,但使用它的索引將是一團糟。所以更好地嘗試'地圖' – Maximin 2013-04-26 03:01:40

回答

0

,你可以簡單的使用與用戶定義的類Map關鍵:

Map<Category, String> map = new HashMap<>(); 

Category可以有屬性,如enumtypePERSONString名稱字段。

確保覆蓋hashCodeequals方法以允許比較不同的Category對象。

0

例如,我會用HashMap作爲鍵名稱和「something」作爲值。

// Create a HashMap which stores Strings as the keys and values 
Map<String,String> example = new HashMap<String,String>(); 

// Adding some values to the HashMap 
example.put("Wayne", new String("Rooney")); 
example.put("Alan", new String("Shearer")); 
example.put("Rio", new String("Ferdinand")); 
example.put("John", new String("Terry")); 

// Find out how many key/value pairs the HashMap contains 
System.out.println("The HashMap contains " + example.size() + " pairs"); 

迭代在地圖上:

for (String key : example.keySet()) { 
    // Get the String value that goes with the key 
    String value = example.get(key); 

    // Print the key and value 
    System.out.println(key + " = " + value); 
} 

更多信息here

-1

你可以試試地圖的地圖:

Map<String, Map<String, V>> map = //... 
//... 

map.get("person").get("name"); 
+0

嘿,有可能做這樣的事情。 map.put(「name」,「xxx」); map.put(「person」,map1.put(「name」,「xxx」));' 因爲有時我可以把字符串和有時地圖。 – 2013-04-26 03:34:04

+0

不,這是不可能的(在第一條語句中)如果map被定義爲Map of Map,那麼你把字符串作爲鍵和值。 – cakil 2013-04-26 03:43:05