2015-04-29 47 views
1

我試圖控制我的應用程序的一些權限。 昨天我學習瞭如何創建雙Brace初始化,它幫助了很多。但現在我想用它嵌套的,但我從IDE(Android Studio中)使用HashMap和List進行嵌套雙括號初始化

這裏得到一個

')' expected 

是我的代碼:

public static final Map<String, List> ALL_PERMISSIONS = new HashMap<String, List>() {{ 
    put("Change-maps", new ArrayList<Integer>(){{add(R.id.button_change_view);}};); 
    put("Stores-info-view", new ArrayList<Integer>(){{add(R.id.details_fragment);}};); 
    put("Competitors-layer", new ArrayList<Integer>(){{add(R.id.switch_concorrentes);}};); 
}}; 

我錯過東西在裏面? 是一個壞的方法?

PS:我正在嘗試這種方法,因爲將來我會使用一些具有多個View(Integer)的鍵和一些具有String列表的鍵。

+0

似乎你錯過了')'在某處......只是檢查大括號小心。 – Yurets

回答

2

如果你看一下這個代碼:

Map<String, String> map = new HashMap<String, String>(); 
map.put("string1", "string2"); 

你可以看到你正在傳遞參數的對象後面沒有;

在你的情況,你通過第二個對象,這是一個:

new ArrayList<Integer>(){{add(R.id.button_change_view);}} 

所以,你不需要前;put的右括號,就像這樣:

public static final Map<String, List> ALL_PERMISSIONS = new HashMap<String, List>() {{ 
     put("Change-maps", new ArrayList<Integer>(){{add(R.id.button_change_view);}}); 
     put("Stores-info-view", new ArrayList<Integer>(){{add(R.id.details_fragment);}}); 
     put("Competitors-layer", new ArrayList<Integer>(){{add(R.id.switch_concorrentes);}}); 
}}; 
3

您應該格式化/縮進您的代碼(默認情況下,在Eclipse中爲Ctrl-Shift-F)。

你會發現你的匿名ArrayList類聲明(外面的一組大括號)不能跟一個分號。

這裏有一個格式化的例子,將工作:

public static final Map<String, List> ALL_PERMISSIONS = new HashMap<String, List>() { 
    { 
     put("Change-maps", new ArrayList<Integer>() { 
      { 
       add(R.id.button_change_view); 
      } 
     }); 
     put("Stores-info-view", new ArrayList<Integer>() { 
      { 
       add(R.id.details_fragment); 
      } 
     }); 
     put("Competitors-layer", new ArrayList<Integer>() { 
      { 
       add(R.id.switch_concorrentes); 
      } 
     }); 
    } 
}; 

注意

而且介意原始類型或抑制警告。

1

我不會鼓勵使用雙支撐固定。作爲this answer解釋說,它可能

  1. 驚喜你的同事和難以辨認
  2. 危害表現
  3. 可能會導致對象平等問題(創建的每個對象都有一個獨特的 類對象)。

我建議,如果可能的話,使用GuavaImmutableMapImmutableList

例如:

public static final Map<String, List> ALL_PERMISSIONS = ImmutableMap.<String, List>of(
     "Change-maps", ImmutableList.of(R.id.button_change_view), 
     "Stores-info-view", ImmutableList.of(R.id.details_fragment), 
     "Competitors-layer", ImmutableList.of(R.id.switch_concorrentes) 
); 

,或者如果您需要添加更多的元素:

public static final Map<String, List> ALL_PERMISSIONS = new ImmutableMap.Builder<String, List>() 
     .put("Change-maps", ImmutableList.of(R.id.button_change_view)) 
     .put("Stores-info-view", ImmutableList.of(R.id.details_fragment)) 
     .put("Competitors-layer", ImmutableList.of(R.id.switch_concorrentes)) 
     //(... and so on... 
     .build();