2013-04-26 56 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