3

我正在尝试在 Java 中实现 Hash of Hashes of Arrays,并认为如果我将使用匿名 blah blah 会很好(我忘记了确切的术语/我不知道如何称呼它)。

HashMap<String, HashMap<String, String[]>> teams = 
    new HashMap<String, HashMap<String, String[]>>(){{
        put("east", new HashMap<String, String[]>(){{
            put("atlantic", new String[] { "bkn", "bos", "phi","tor", "ny" });
            put("central", new String[] { "chi", "cle", "det", "ind", "mil" });
            put("southeast", new String[] { "atl", "cha", "mia", "orl", "wsh" });
        }});
        put("west", new HashMap<String, String[]>(){{
            put("northwest", new String[] { "den", "min", "okc", "por", "utah" });
            put("pacific", new String[] { "gs", "lac", "lal", "phx", "sac" });
            put("southwest", new String[] { "dal", "hou", "mem", "no", "sa" });
        }});
    }};

我的问题是,是否有另一种考虑可读性的实现方式,或者完全改变实现方式?我知道 java 不是正确的工具,但我的老板告诉我这样做。另外,请让我知道正确的术语。TIA

4

2 回答 2

3

只要我们不关心运行速度,为什么不使用一种旨在表达分层数据结构的语言,如 JSON 呢?JAVA 对它有很好的外部库支持...

格森来救场!

    @SuppressWarnings("unchecked")
    HashMap teams = 
    new Gson().fromJson(
        "{'east' : { 'atlantic'  : ['bkn', 'bos', 'phi','tor', 'ny']," +
        "            'central'   : ['chi', 'cle', 'det', 'ind', 'mil']," +
        "            'southeast' : ['atl', 'cha', 'mia', 'orl', 'wsh']}," +
        " 'west' : { 'northwest' : ['den', 'min', 'okc', 'por', 'utah']," +
        "            'pacific'   : ['gs', 'lac', 'lal', 'phx', 'sac']," +
        "            'southwest' : ['dal', 'hou', 'mem', 'no', 'sa']}}",
        HashMap.class
    );

http://code.google.com/p/google-gson/

于 2012-11-20T14:55:05.180 回答
2

使用辅助方法

private void addTeams(String area, String codes) {
    String[] areas = area.split("/");
    Map<String, String[]> map = teams.get(areas[0]);
    if (map == null) teams.put(areas[0], map = new HashMap<String, String[]>());
    map.put(areas[1], codes.split(", ?"));
}

Map<String, Map<String, String[]>> teams = new HashMap<String, Map<String, String[]>>();{
    addTeams("east/atlantic", "bkn, bos, phi, tor, ny");
    addTeams("east/central", "chi, cle, det, ind, mil");
    addTeams("east/southeast", "atl, cha, mia, orl, wsh");
    addTeams("west/northwest", "den, min, okc, por, utah");
    addTeams("west/pacific", "gs, lac, lal, phx, sac");
    addTeams("west.southwest", "dal, hou, mem, no, sa");
}

你可以更换

new String[] { "bkn", "bos", "phi","tor", "ny" }

"bkn,bos,phi,tor,ny".split(",");
于 2012-11-20T14:24:42.050 回答