如何解决如何在Java中使用List变量制作对象的深层副本?
我正在使用 Java 并且我想制作一个 MoleculeDTO 对象的深层副本。我也尝试创建一个复制构造函数,但它不起作用,它引用了初始对象。
public class MoleculeDTO {
private int ID;
private String name;
private List<AtomDTO> atoms = new ArrayList<>();
private int nrAtoms =0;
public MoleculeDTO(String name,List<AtomDTO> atoms,int nrAtoms) {
this.name = name;
this.atoms = atoms;
this.nrAtoms = nrAtoms;
}
public MoleculeDTO(MoleculeDTO molecule) {
this(molecule.getName(),molecule.getAtoms(),molecule.getNrAtoms());
}
...getter,setter
}
这是 AtomDTO 类。
public class AtomDTO{
private int ID;
private String name;
private String symbol;
private int nrOfBonds;
private List<BondDTO> bonds = new ArrayList<>();
private int type;
private AnchorNode anchorNode;
public AtomDTO(String name,String symbol,int nrOfBonds,List<BondDTO> bonds,int type) {
this.name = name;
this.nrOfBonds = nrOfBonds;
this.bonds = bonds;
this.type = type;
}
public AtomDTO(AtomDTO copyAtom) {
this(copyAtom.getName(),copyAtom.getSymbol(),copyAtom.getNrOfBonds(),copyAtom.getBonds(),copyAtom.getType());
}
...getter,setter
}
这是 BondDTO 类。
public class BondDTO {
private int ID;
private int otherAtomID;
private int otherAtomType;
private int bondType;
public BondDTO(int otherAtomID,int otherAtomType,int bondType) {
this.otherAtomID = otherAtomID;
this.otherAtomType = otherAtomType;
this.bondType = bondType;
}
public BondDTO(BondDTO copyBond) {
this(copyBond.getOtherAtomID(),copyBond.otherAtomType,copyBond.bondType);
}
...getter,setter
}
解决方法
您的复制构造函数只是对每个字段进行浅复制。这对字符串很好,因为它们是不可变的,对 int 也很好,因为它们是原始的(这意味着它们缺乏身份并且是不可变的)。在这些情况下,浅拷贝和深拷贝之间没有重要区别。但它通常不适用于列表,因为列表可以是可变的,它们的元素也是如此。因此,您需要创建一个新列表并将原始列表的每个元素深度复制到新列表中,而不是仅仅指向同一个列表。
使用此辅助方法制作任何列表的深层副本:
static <T> List<T> deepCopyList(List<T> list,UnaryOperator<T> deepCopyElement) {
return list.stream().map(deepCopyElement).collect(
Collectors.toCollection(ArrayList::new)
);
}
像这样:
public AtomDTO(AtomDTO that) {
this(that.getName(),that.getType(),deepCopyList(that.getBonds(),BondDTO::new));
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。