【发布时间】:2018-02-22 11:41:17
【问题描述】:
我试图让我的代码将一个名为 primitive 的 OutputData 对象克隆到一个列表中,为我正在制作的每个克隆更改一个 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]]
【问题讨论】: