2012-11-20 168 views
3

我试图在Java中实现哈希数组哈希,并认为这将是很好,如果我将使用匿名等等等等(我忘了确切的术语/我不知道如何调用它)。Java中的哈希数组哈希

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

+0

您是不是要找'匿名内部classes'? – SJuan76

+0

也许你的意思是把这一个codereview.stackexchange.com – durron597

+0

@ durron597我即将这样做,但我想知道替代品。我会更新我的问题,谢谢。 – jchips12

回答

3

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

Gson来救援!

@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/

+0

+1不错的解决方案 – maasg

+0

我终于决定使用Gson和一个json文件(由@ durron597建议) – jchips12

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(","); 
+2

这更可读,但不是更慢? – durron597

+1

我不会推荐这个。它增加额外的工作,收益甚微。 – gbtimmon

+0

它会使您的启动速度减慢几个微秒,即使在低交易延迟系统中也很少出现这种情况。 –