java - 返回时数组列表为空

标签 java android collections

我正在做一个 android 项目,我遇到了一个问题,问题是:

Arraylist empty when I return it.

这是我的java代码:

 ArrayList<ArrayList<Object>> container = new ArrayList<ArrayList<Object>>();
            ArrayList<Object> itemRow = new ArrayList<Object>();
            JSONObject jsonObj =  new JSONObject(result);
            JSONArray allElements = jsonObj.getJSONArray("Table");
            Log.i("allElements", "" + allElements);
            for (int i = 0; i < allElements.length(); i++) {
                itemRow.add(allElements.getJSONObject(i).getString("ParentName").toString());
                itemRow.add(allElements.getJSONObject(i).getString("ParentEmailID").toString());
                itemRow.add(allElements.getJSONObject(i).getString("ParentContact").toString());
                itemRow.add(allElements.getJSONObject(i).getString("ParentAddress").toString());
                itemRow.add(allElements.getJSONObject(i).getString("ParentProfilePictureName").toString());
                itemRow.add(allElements.getJSONObject(i).getString("StudentName").toString());
                Log.i("itemRow", "itemRow at index: " + i + ", " + itemRow);
                container.add(((i*2)/2), itemRow);
                itemRow.clear();
            }

            return container;

在这段代码中,我有两个 Arraylist,一个用于包含所有元素,另一个用于存储单行元素。这些 Arraylist 是从 JSONArray 加载的,一切正常,我可以从项目行(采用单行的 Arraylist)打印数据并存储到主 Arraylist(容器)中。

但是当我返回这个 Arraylist(容器)并在 logcat 中打印时,它显示空的 Arraylist,如

[[], [], [], [], []].

我不明白为什么会这样,请帮我解决这个问题。

谢谢。

最佳答案

因为你做了,它仍然引用添加到container的对象

itemRow.clear();

你可能想重新初始化它

itemRow = new ArrayList<Object>();

关于java - 返回时数组列表为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11206057/

相关文章:

java - 具有 Collection 字段的对象的 GSON 自定义序列化程序

java - 如何一次性从Set中获取数据

java - 用于批量发送电子邮件的 jars

java - 将表记录映射到 JPA 实体

android - 开始使用新的 Firebase 网站,我在测试 Android 身份验证示例程序时遇到此错误

Android Studio Gradle 找不到方法编译()

java - 从 List<MyData> 列出 List<String> 中的所有名称的最佳方法是什么

java - 如何检查批处理文件是否正在 Windows 上运行?

java - 使用 Maven 2 构建可运行的 jar

java - 如何在 android studio 中将 GONE 可见性更改为 VISIBLE 可见性