在嵌套for循环中迭代ArrayList导致意外结果

时间:2019-04-11 08:59:27

标签: java android arraylist expandablelistview

我想在Android中使用this示例来实现带有标题和某些子问题的Expandable Recycleview。

在为Expandable Adapter构造数据时,我面临这样的问题。

这是我对API的回复

            [{
                "Label": "Title One",
                "Question": "SubQuestion One "
            },
            {
                "Label": "Title One"
                "Question": "SubQuestion Two"
            },
            {
                "Label": "Title Two",
                "Question": "SubQuestion Three"
            },
            {
                "Label": "Title Two",
                "Question": "SubQuestion Four"
            },
            {
                "Label": "Title Two",
                "Question": "SubQuestion Five"
            }]

我想用Label分隔每个标题为Title 1且与Title 2相同的问题,所以我做了以下事情

第1步:创建标签ArrayList并从ArrayList中删除重复项

for (int j = 0; j < temp.size(); j++) {
ProgramDefinitionV1Days data = temp.get(j);
mAllTitlesList.add(data.getLabel());
}
mCompareTitlesList.clear();
mCompareTitlesList = removeDuplicates(mAllTitlesList);

第2步:将mCompareTitlesList与原始响应进行比较,并按标签获取问题

for (String label : mCompareTitlesList) {
mQuetionsList.clear();
for (int i = 0; i < temp.size(); i++) {
    if (label.equalsIgnoreCase(temp.get(i).getLabel())) {

        mQuetionsList.add(new Questions(temp.get(i).getQuestion()));
    }

}
Log.e("mQuetionsList", "" + new Gson().toJson(mQuetionsList));
Titles mTitles = new Titles(label, mQuetionsList);
mTitlesList.add(mTitles);
}

但不幸的是,我没有从表格中获得预期结果。

[{"mQuestions":[{"mQuestions":"Question Three"},{"mQuestions":"Question Four"},{"mQuestions":"Question Five"}],"mTitle":"Title One"},{"mQuestions":[{"mQuestions":"Question Three"},{"mQuestions":"Question Four"},{"mQuestions":"Question Five"}],"mTitle":"Title Two"}]

在每个标签上都有所有最后一个标签的问题

我期望

[{"mQuestions":[{"mQuestions":"Question One"},{"mQuestions":"Question Two"}],"mTitle":"Title One"},{"mQuestions":[{"mQuestions":"Question Three"},{"mQuestions":"Question Four"},{"mQuestions":"Question Five"}],"mTitle":"Title Two"}]

任何建议吗?

0 个答案:

没有答案