Java HashMap associative multi dimensional array can not create or add elements

前端 未结 4 1247
小蘑菇
小蘑菇 2020-12-09 17:33

Okay so I have spent several hours trying to wrap my head around this concept of a HashMap in Java but am just not able to figure it out. I have looked at many tutorials but

4条回答
  •  半阙折子戏
    2020-12-09 17:57

    Unfortunately, there's no concise syntax for constructing populated maps in Java. You'll have to write it out long-hand. A separate helper method can make it a little simpler:

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

    Then:

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

    You would retrieve it with:

    english_name = myArray.get("en").get("name");
    

提交回复
热议问题