17

好的,所以我花了几个小时试图围绕 Java 中的 HashMap 这个概念进行思考,但我只是无法弄清楚。我看过很多教程,但似乎没有一个能满足我的确切要求,我无法让它工作。

我正在尝试在Java(或类似的东西)中创建一个关联的多维数组,以便我可以使用字符串键来保存和检索数组。

这就是我在 PHP 中的做法,并最好地解释了我正在尝试做的事情:

//loop one - assign the names
myArray['en']['name'] = "english name";
myArray['fr']['name'] = "french name";
myArray['es']['name'] = "spanish name";

//loop two - assign the description
myArray['en']['desc'] = "english description";
myArray['fr']['desc'] = "french description";
myArray['es']['desc'] = "spanish description";

//loop three - assign the keywords
myArray['en']['keys'] = "english keywords";
myArray['fr']['keys'] = "french keywords";
myArray['es']['keys'] = "spanish keywords";

//later on in the code be able to retrive any value similar to this
english_name = myArray['en']['name'];
french_name = myArray['fr']['name'];
spanish_name = myArray['es']['name'];

这是我在 Java 中尝试过的,但它不起作用:

HashMap<String, HashMap<String, String>> myArray = new HashMap<String, HashMap<String, String>>();

myArray.put("en" , put("name", "english name")); //gives me "cannot find symbol" at second put

myArray.put("en" , ("name", "english name")); //gives me "')' expected" after second comma

所以我确信我错过了一些简单的东西,但请指出,因为这非常令人沮丧!

谢谢

编辑:

所以这里有一些关于我如何实现我接受的答案的工作代码:

import java.util.*;

HashMap<String, HashMap<String, String>> finalArray = new HashMap<String, HashMap<String, String>>();

String[] langArray = {"en","fr","de","no","es"};

//Initialize each language key ahead of time
for(String lang : langArray) { // foreach lang in langArray
  if (!finalArray.containsKey(lang)) {
    finalArray.put(lang, new HashMap<String, String>());
  }
}

//loop one - assign names
for(String lang : langArray) {
  String theName = lang + " name"; //go get the name from somewhere
  finalArray.get(lang).put("name", theName);
}

//loop two - assign description
for(String lang : langArray) {
  String theDesc = lang + " description"; //go get the description from somewhere
  finalArray.get(lang).put("desc", theDesc);
}

//loop three - assign keywords
for(String lang : langArray) {
  String theKeys = lang + " keywords"; //go get the keywords from somewhere
  finalArray.get(lang).put("keys", theKeys);
}

//display output
for(String lang : langArray) {
  System.out.println("LANGUAGE: " + lang);
  System.out.println(finalArray.get(lang).get("name"));
  System.out.println(finalArray.get(lang).get("desc"));
  System.out.println(finalArray.get(lang).get("keys"));
}

//example to retrieve/get values
String english_name = finalArray.get("en").get("name");
String french_desc = finalArray.get("fr").get("desc");
4

5 回答 5

21
HashMap<String, HashMap<String, String>> myArray = new HashMap<String, HashMap<String, String>>();

if (!myArray.containsKey("en")) {
    myArray.put("en", new HashMap<String, String>());
}
myArray.get("en").put("name", "english name");

在 Java 中,您必须明确何时创建对象。在这种情况下,首先我们检查是否已经有一个HashMap对象存储在我们的外部HashMap键“en”下。如果没有,我们创建一个空的。

现在要将新值放入其中,我们必须首先从外部获取它HashMap,然后放入新值。

于 2013-08-20T03:20:54.450 回答
4
HashMap<String, HashMap<String, String>> myArray = new HashMap<String, HashMap<String, String>>();
HashMap<String, String> value = new HashMap<String, String>();
value.put("name", "English name");
value.put("desc", "English description");
value.put("keys", "English keywords");

myArray.put("en" , value);

value = new HashMap<String, String>();
value.put("name", "French name");
value.put("desc", "French description");
value.put("keys", "French keywords");

myArray.put("fr" , value);
于 2013-08-20T03:24:54.957 回答
3

不幸的是,没有用于在 Java 中构建填充地图的简洁语法。你必须把它写出来。一个单独的辅助方法可以使它更简单一些:

HashMap<String, String> makeMap(String name, String desc, String keys) {
    HashMap<String, String> map = new HashMap<>();
    // Before Java 7, above must be: new HashMap<String, String>();
    map.put("name", name);
    map.put("desc", desc);
    map.put("keys", keys);
}

然后:

HashMap<String, HashMap<String, String>> myArray = new HashMap<>();
myArray.put("en",
    makeMap("english name", "english description", "english keywords"));
// etc.

您可以通过以下方式检索它:

english_name = myArray.get("en").get("name");
于 2013-08-20T03:21:43.820 回答
1
import java.util.HashMap;
public class Main
{
    public static void main(String[] args) {
        // Creating array
        HashMap<String, HashMap<String, String>> myArray = new HashMap<String, HashMap<String, String>>();
        // Setting values
        for(int i=0; i<100;i++) {
            myArray.put("key1"+i, new HashMap<String, String>());
            myArray.get("key1"+i).put("key2"+i, "value"+i);
        }
        // Getting values
        for(int i=0; i<100; i++) {
        System.out.println(myArray.get("key1"+i).get("key2"+i));
        }
    }
}
于 2019-09-20T10:02:55.327 回答
0

我真的很喜欢“dAv dEv”的例子,尽管他并没有真正填充他的双键数组(我在循环中添加了一个循环)。我也比 HashMaps 更喜欢 TreeMaps,因为它们不是随机的。

import java.util.Map;
import java.util.TreeMap;

TreeMap<String, TreeMap<String, String>> myArray = 
                    new TreeMap<String, TreeMap<String, String>>();
String[] roles = { "Help Desk", "Administrator", "Super Use", ... };
String[] elements = { "Hydrogen", "Helium", "Lithium", "Beryllium", ... };

// Setting values TODO: read data values from Excel spreadsheet (or wherever)
for(String role : roles) {
        myArray.put(role, new TreeMap<String, String>());
        for (String elementName : elements) {
            String value = Utils.getHumanName("first", true);
            myArray.get(role).put(elementName, value);
        }
}
// Getting values
for (Map.Entry<String,TreeMap<String,String>> entry1 : myArray.entrySet()) {
    String key1 = entry1.getKey();
    TreeMap<String,String> value1 = entry1.getValue();
    for (Map.Entry<String,String> entry2 : value1.entrySet()) {
            String key2 = entry2.getKey();
            String value2 = entry2.getValue();
            System.out.println("(" + key1 + ", " + key2 + ") = " +
                                       myArray.get(key1).get(key2));
    }
}

PS 我使用 Utils.getHumanName() 作为我的数据生成器。您将需要使用自己的。

于 2021-02-26T04:26:46.310 回答