2012-11-20 213 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

它會使您的啓動速度減慢幾個微秒,即使在低交易延遲系統中也很少出現這種情況。 –