gpt4 book ai didi

java - 将对象克隆到列表中,并为每个项目更改多个值

转载 作者:行者123 更新时间:2023-12-02 11:36:03 26 4
gpt4 key购买 nike

我正在尝试让我的代码将名为 primitiveOutputData 对象克隆到列表中,为我正在创建的每个克隆更改 int 值。这是我想出的代码:

public void fixAndSave(){
for(int i = 1; i <= NUM_EXEC; i++){
InputData custom = new InputData(primitive);
for (Section s : custom.getSections()){
if (s.getId() != 0 )
s.setBloques(i*s.getId());
}
collection.add(custom);
System.out.println("GUARDANDO DATA: " + custom.getSections().toString());

}
collection.forEach((InputData d) -> {
System.out.println("DATA GUARDADO: " + d.getSections().toString());
});
}

我的问题是,当我检查结果时,仅保存最后一个值并为每个克隆对象重复,因此我猜测我正在以某种方式复制对该对象的整个引用。我应该如何正确地做到这一点,以便每个对象都包含正确的信息?

这是该方法的输出:

//This values are correct and are the ones I want
GUARDANDO DATA: [Section [id=0, length=7.5, bloques=0], Section [id=1, length=7.5, bloques=1], Section [id=2, length=7.5, bloques=2], Section [id=3, length=7.5, bloques=3]]

GUARDANDO DATA: [Section [id=0, length=7.5, bloques=0], Section [id=1, length=7.5, bloques=2], Section [id=2, length=7.5, bloques=4], Section [id=3, length=7.5, bloques=6]]

GUARDANDO DATA: [Section [id=0, length=7.5, bloques=0], Section [id=1, length=7.5, bloques=3], Section [id=2, length=7.5, bloques=6], Section [id=3, length=7.5, bloques=9]]

GUARDANDO DATA: [Section [id=0, length=7.5, bloques=0], Section [id=1, length=7.5, bloques=4], Section [id=2, length=7.5, bloques=8], Section [id=3, length=7.5, bloques=12]]

// This values are incorrect and saved in the list
DATA GUARDADO: [Section [id=0, length=7.5, bloques=0], Section [id=1, length=7.5, bloques=4], Section [id=2, length=7.5, bloques=8], Section [id=3, length=7.5, bloques=12]]

DATA GUARDADO: [Section [id=0, length=7.5, bloques=0], Section [id=1, length=7.5, bloques=4], Section [id=2, length=7.5, bloques=8], Section [id=3, length=7.5, bloques=12]]

DATA GUARDADO: [Section [id=0, length=7.5, bloques=0], Section [id=1, length=7.5, bloques=4], Section [id=2, length=7.5, bloques=8], Section [id=3, length=7.5, bloques=12]]

DATA GUARDADO: [Section [id=0, length=7.5, bloques=0], Section [id=1, length=7.5, bloques=4], Section [id=2, length=7.5, bloques=8], Section [id=3, length=7.5, bloques=12]]

最佳答案

您需要执行深度复制,并在调用时考虑 getSections() 返回的字段:

InputData custom = new InputData(primitive);

它可能看起来像:

public InputData(OutputData outputData){
// ...
List<Section> copiedSections = new ArrayList<>();
for (Section section : outputData.getSections()){
Section copiedSection = new Section(section); // copy constructor
copiedSections.add(copiedSection);
}
this.sections = copiedSections;
}

关于java - 将对象克隆到列表中,并为每个项目更改多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48926532/

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