簡體   English   中英

在arraylist的arraylist中動態添加arraylist

[英]Dynamically add arraylist in arraylist in arraylist

我試圖在arraylist的arraylist中添加一個arraylist,但是在連續進行第一個循環之后,添加下一個插入的第一個數組。

 List<ArrayList<List<String>>> tlist= new ArrayList<>();
 List<List<String>> tslist= new ArrayList<>();
 List<String> childcat= new ArrayList<>();
 for (int i = 0; i < response.length(); i++) {
     JSONObject person = (JSONObject) response.get(i);
     for (int j = 0; j < sub.length(); j++) {
         JSONObject subobj = sub.optJSONObject(j);
         JSONArray suba = subobj.optJSONArray("SubMenus");
         childcat = new ArrayList<>();
         if(suba!=null) {
             for (int k = 0; k < suba.length(); k++) {
                 JSONObject subobja = suba.optJSONObject(k);
                 childcat.add(subtitlea);
             }
         }
         tslist.add(new ArrayList<String>(childcat));
     }
     tlist.add((new ArrayList<>(tslist)));  
 }

@Maroun Maroun對問題的評論。

如果您堅持使用此代碼;

將其添加到列表后,創建一個新對象(Arraylist)。 不需要在第一個循環之前創建所有對象。 嘗試如下

     List<ArrayList<List<String>>> tlist= new ArrayList<>();
     for (int i = 0; i < response.length(); i++) {
         JSONObject person = (JSONObject) response.get(i);
         List<List<String>> tslist= new ArrayList<>();
         for (int j = 0; j < sub.length(); j++) {
             JSONObject subobj = sub.optJSONObject(j);
             JSONArray suba = subobj.optJSONArray("SubMenus");
             List<String> childcat= new ArrayList<>();
             if(suba!=null) {
                 for (int k = 0; k < suba.length(); k++) {
                     JSONObject subobja = suba.optJSONObject(k);
                     childcat.add(subtitlea);
                 }
             }
             tslist.add(new ArrayList<String>(childcat));
         }
         tlist.add((new ArrayList<>(tslist)));  
     }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM