为什么在组合多个ArrayLists时会出现重复项?

时间:2014-01-08 03:07:06

标签: java arraylist duplicates

为什么我在ArrayList<String[]>中收到重复的条目?

  • allStepsJSONStringArray包含格式为JSON的单个字符串数组
  • 我遍历并将每个JSON字符串传递给将其写入临时内部文件的函数
  • 我读了文件
  • 然后将其传递给getStepsArray(),分解JSON字符串并将每个条目放入String[]

循环添加到主ArrayList - allStepsArray

for (int i = 0; i < allStepsJSONStringArray.size(); i++) {
    writer.writeToInternal(allStepsJSONStringArray.get(i));
    reader.readFromInternal(writer.filename); 
    stepsArray = reader.getStepsArray();
    for (int s = 0; s < stepsArray.size(); s++) {
        allStepsArray.add(stepsArray.get(s));
    }
}

getStepsArray()

public ArrayList<String[]> getStepsArray() {
    try {
        JSONObject jObject = new JSONObject(jsonString);
        JSONArray jArray = jObject.getJSONArray("steps");
        String stepOrder = null;
        String stepName = null;
        String stepType = null;
        String stepId = null;
        String checklistId = null;
        String checklistName = null;

        for (int i = 0; i < jArray.length(); i++) {
            stepOrder = jArray.getJSONObject(i).getString("order");
            stepName = jArray.getJSONObject(i).getString("name");
            stepType = jArray.getJSONObject(i).getString("type");
            stepId = jArray.getJSONObject(i).getString("id");
            checklistId = jObject.getString("checklistId");
            checklistName = jObject.getString("checklistName");
            stepsArray.add(new String[] {stepOrder, stepName, stepType, stepId, checklistName, checklistId});
        }


    } catch (Exception e) {
        e.printStackTrace();
    }
    return stepsArray;
}

1 个答案:

答案 0 :(得分:1)

一字不漏:

因为您似乎没有重置stepsArray。第二次向其中添加元素时,之前的元素仍然存在,并会再次添加到allStepsArray