3

我是Java新手,所以我对它了解不多。当我在 Java 中发现一些非常令人沮丧的东西时,我正在使用 Array。

我有一个字符串数组,我希望索引是一个字符串。例如

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

但是 Java 不允许我这样做。请帮助我解决这个问题或一些解决方法。谢谢

4

3 回答 3

0

You can try map of maps:

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

map.get("person").get("name");
于 2013-04-26T03:05:57.140 回答
0

您可以简单地将 aMap与用户定义的类一起用作键:

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

Category可以具有诸如enum type诸如PERSONString名称字段之类的属性。

确保覆盖hashCodeequals方法以允许Category比较不同的对象。

于 2013-04-26T02:58:36.290 回答
0

例如,我将使用HashMap名称作为键,将“某物”作为值。

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

更多信息在这里

于 2013-04-26T02:59:00.027 回答