【问题标题】:Dynamically add arraylist in arraylist in arraylist在arraylist中动态添加arraylist
【发布时间】:2016-03-22 08:51:47
【问题描述】:

我正在尝试在 arraylist 中的 arraylist 中添加一个 arraylist,但是在第一个循环之后连续添加第一个数组 insted 的下一个..

 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)));  
 }

【问题讨论】:

  • subtitlea 声明在哪里?
  • 拥有一个列表或列表的arraylist 是糟糕设计的标志。尝试封装你的结构。
  • 你真正想做什么?也许会更容易..
  • 我想稍后使用它来创建一个三级可扩展列表视图。问题是 tlist 没有正确实例化并且它导致了问题。

标签: java android multidimensional-array


【解决方案1】:

收听@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)));  
     }

【讨论】:

    猜你喜欢
    • 2015-03-30
    • 2017-09-13
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    • 2013-04-25
    • 2014-08-03
    • 2018-08-16
    • 2014-03-23
    相关资源
    最近更新 更多