gpt4 book ai didi

java - 如何在java列表中使用addall

转载 作者:行者123 更新时间:2023-12-02 08:00:36 24 4
gpt4 key购买 nike

您好,我必须将元素添加到我的列表中,我注意到如果我使用 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.

}

最佳答案

您每次都添加相同的ArrayState对象。您应该每次在 while 循环中创建一个新的 ArrayState 对象,以避免每次都发生更改。这是因为默认情况下,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);

}

关于java - 如何在java列表中使用addall,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8969318/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com