如何在列表java中使用addall

时间:2012-01-23 09:17:02

标签: java list add

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

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.

}

2 个答案:

答案 0 :(得分:1)

这里的问题是你有一个&#34; arrayState&#34;对象和所有状态对象引用相同的对象。

解决这个问题的一种方法是在循环中移动对象,以便每次都创建不同的对象。

 while(rs.next) {
      List<State> arrayState = new ArrayList<State>();
      ...
 }

答案 1 :(得分:1)

您每次都要添加相同的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);

}
相关问题