简体   繁体   English

如何在列表java中使用addall

[英]How to use addall in a list java

Hello I have to add elements to my list and I notice if I Use the method add I just add the reference to my list but I would like to add the elements and not the reference: 您好我必须在我的列表中添加元素,我注意到如果我使用方法添加我只是添加对我的列表的引用但我想添加元素而不是引用:

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.

}

The problem here is that you have one "arrayState" object and all of the state objects reference the same one. 这里的问题是你有一个“arrayState”对象,所有状态对象引用相同的对象。

One way to solve that here is to move the object creation inside loop so that a different object is created every time. 解决这个问题的一种方法是在循环内移动对象,以便每次都创建一个不同的对象。

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

You are adding the same ArrayState object every time. 您每次都添加相同的ArrayState对象。 You should create a new ArrayState object every time in the while loop to avoid it getting changed every time. 您应该每次在while循环中创建一个新的ArrayState对象while以避免每次都更改它。 This is because by default objects are always passed by reference in Java. 这是因为默认情况下,对象总是通过Java引用传递。 Try doing this: 试着这样做:

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);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM