Par*_*ari 1 java collections android
我正在研究一个Android项目,我遇到了一个问题,问题是:
当我退回时,Arraylist为空.
这是我的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;
Run Code Online (Sandbox Code Playgroud)
在这段代码中,我有两个Arraylist用于包含所有元素,另一个用于存储单行元素.这些Arraylist是从JSONArray加载的,一切正常,我可以从项目行(Arraylist,单行)打印数据并存储到主Arraylist(容器).
但是当我返回这个Arraylist(容器)并在logcat中打印时,它会显示空的Arraylist
[[], [], [], [], []].
Run Code Online (Sandbox Code Playgroud)
我不明白为什么会发生这种情况请帮我解决这个问题.
谢谢.
因为你做了,它仍然引用添加到的对象 container
itemRow.clear();
Run Code Online (Sandbox Code Playgroud)
您可能想要重新初始化它
itemRow = new ArrayList<Object>();
Run Code Online (Sandbox Code Playgroud)
停止清除列表,它不再是空的:
itemRow.clear();
Run Code Online (Sandbox Code Playgroud)
您应该在每次迭代时创建一个新列表.将以下代码行放在for循环中:
ArrayList<Object> itemRow = new ArrayList<Object>();
Run Code Online (Sandbox Code Playgroud)
请记住,Java传递对象的引用.因此容器列表包含对您添加到其中的列表的引用.它不会复制列表.因此,您当前的代码会将相同列表对象的多个引用添加到容器列表中,并在每次添加时清除列表.因此它在循环结束时包含对相同空列表的N个引用.
| 归档时间: |
|
| 查看次数: |
248 次 |
| 最近记录: |