您好,我必须将元素添加到列表中,我注意到如果使用添加方法,我只是将引用添加到列表中,但我想添加元素而不是引用:

ArrayList ArrayListIdle = new ArrayList();
List<State> arrayState = new ArrayList<State>();

while(rs.next){

state = new State();

state.updateStateArray(arrayState);//This function mods the elements of (arrayState);//This
state.setArrayStates(arrayState);//add a list of arrayState to the object state


//I have a array and I want to add the element state with his arraylist(not the reference to)

ArrayListIdle.addAll(state);

// I tried with add , but in the next iteration the arrayState change.

}

最佳答案

您每次都添加相同的ArrayState对象。您应该每次在ArrayState循环中创建一个新的while对象,以避免每次更改该对象。这是因为默认情况下,在Java中始终通过引用传递对象。
尝试这样做:

ArrayList arrayListIdle = new ArrayList();


while(rs.next){

    state = new State();
    List<State> arrayState = new ArrayList<State>();

    state.updateStateArray(arrayState);//This function mods the elements of (arrayState);//This
    state.setArrayStates(arrayState);//add a list of arrayState to the object state
    arrayListIdle.addAll(state);

}

09-20 17:22