如何使用Java迭代ArrayList值?

时间:2017-06-30 16:54:55

标签: java arraylist collections

这是我在Subject bean中的实际数据

[
    {
        "subbat": [
            {
                "batn": "A1",
            },
            {
                "batn": "A2",
            }
        ],
        "id": "588edaf7adbe1d00013ff125"
    }

]

我想基于我想要创建的subbat大小重写这个bean并设置一个字段“batn”

{
    "subbat": [
        {
            "batn": "A1",
        },
        {
            "batn": "A2",
        }
    ],
    "batn": "A1",                 -------//trying to set batn
    "id": "588edaf7adbe1d00013ff125"
},
{
    "subbat": [
        {
            "batn": "A1",
        },
        {
            "batn": "A2",
        }
    ],
    "batn": "A2",             -------//trying to set batn
    "id": "588edaf7adbe1d00013ff125"
},

但我得到了这个输出 - batn = A2

{
    "subbat": [
        {
            "batn": "A1",
        },
        {
            "batn": "A2",
        }
    ],
    "batn": "A2",------------------------------->I got A2 here why?
    "id": "588edaf7adbe1d00013ff125"
},
{
    "subbat": [
        {
            "batn": "A1",
        },
        {
            "batn": "A2",
        }
    ],
    "batn": "A2",
    "id": "588edaf7adbe1d00013ff125"
},

这是我在此代码中尝试此错误的代码

List<Subject> subjects = new ArrayList<Subject>();
for (Subject eachSubject : subjectDatas) {
    if (eachSubject.getSubbat() != null && !eachSubject.getSubbat().isEmpty()) {
    for (Batch eachBatch : eachSubject.getSubbat()) {
        if (eachBatch.getBatn() != null) {
        eachSubject.setBatn(eachBatch.getBatn());
        subjects.add(eachSubject);
        }

    }
    } else {
    subjects.add(eachSubject);
    }
}

我也使用了迭代器方式,但输出相同是逻辑错误

List<Subject> subjects = new ArrayList<Subject>();
ListIterator<Subject> iter = subjectDatas.listIterator();
while (iter.hasNext()) {
    Subject eachSubject = iter.next();
    if (eachSubject.getSubbat() != null && !eachSubject.getSubbat().isEmpty()) {
    ListIterator<Batch> iter1 = eachSubject.getSubbat().listIterator();
    while (iter1.hasNext()) {
        Batch eachBatch = iter1.next();
        eachSubject.setBatn(eachBatch.getBatn());
        subjects.add(eachSubject);
    }
    } else {
    subjects.add(eachSubject);
    }
}

我的代码发生了哪些变化?

2 个答案:

答案 0 :(得分:0)

问题在于eachSubject对象。 如果您注意到,您的内部for循环正在将SAME外部对象添加到主题列表中。即使您在内部循环的第一次迭代中设置了正确的值,该对象也会在后续迭代中被修改...这最终将导致添加相同的对象n次,并且所有新的主题列表对象将包含最后一次被覆盖的对象值。 所以不要反复修改同一个对象,这应该修复重复

答案 1 :(得分:0)

如果不是,请使您的主题可克隆(深度克隆)。然后你可以在你的内循环中使用下面的内容。

Subject newSubject = eachSubject.clone();
Batch eachBatch = iter1.next();
newSubject.setBatn(eachBatch.getBatn());
subjects.add(newSubject);