【发布时间】:2015-08-17 21:10:34
【问题描述】:
我有一个包含 2 个位置的数组,每个位置包含一个“ids_alunos”列表,第一个位置有 ids_alunos:“1,2,3”,第二个:“4,5”,但是当我添加时会发生什么我的数组中的 id 是这样的,第一个位置获得“1,2,3”值,第二个位置:“1,2,3,4,5”。为什么会这样?
public ArrayList<CadastraEscolas> getFilhos(String mToken) throws Exception {
String[] resposta = new WebService().get("filhos", mToken);
if (resposta[0].equals("200")) {
JSONObject mJSONObject = new JSONObject(resposta[1]);
JSONArray dados = mJSONObject.getJSONArray("data");
mArrayList = new ArrayList<CadastraEscolas>();
mGPSList = new ArrayList<GPSEscolas>();
for (int i = 0; i < dados.length(); i++) {
JSONObject item = dados.getJSONObject(i).getJSONObject("escolas");
JSONArray escolas = item.getJSONArray("data");
for (int j = 0; j < escolas.length(); j++) {
JSONObject jItens = escolas.getJSONObject(j);
mCadastraEscolas = new CadastraEscolas();
mGPSEscolas = new GPSEscolas();
mCadastraEscolas.setId_escola(jItens.optInt("id_escola"));
mGPSEscolas.setId_escola(jItens.optInt("id_escola"));
JSONObject alunos = jItens.optJSONObject("alunos");
JSONArray data = alunos.getJSONArray("data");
if (data != null) {
ArrayList<Filhos> arrayalunos = new ArrayList<Filhos>();
for (int a = 0; a < data.length(); a++) {
mFilhos = new Filhos();
JSONObject clientes = data.getJSONObject(a);
mFilhos.setId_aluno(clientes.optInt("id_aluno"));
arrayalunos.add(mFilhos);
idsAlunos += ";" + arrayalunos.get(a).getId_aluno().toString();
mGPSEscolas.setIds_alunos(idsAlunos);
}
mCadastraEscolas.setalunos(arrayalunos);
}
mArrayList.add(mCadastraEscolas);
mGPSList.add(mGPSEscolas);
}
}
return mArrayList;
} else {
throw new Exception("[" + resposta[0] + "] ERRO: " + resposta[1]);
}
}
【问题讨论】:
-
idsAlunos的声明在哪里?如果它具有全局范围,则第一次迭代的值将保留到第二次迭代,因此附加到第一个值。如果你想避免这种情况,要么给 idsAlunos 局部范围,要么在每次迭代开始时清除值 -
使用 Set 而不是 ArrayList 以避免重复值。
标签: java android arrays multidimensional-array arraylist