有一个名为 foo 的类 (class0)。
我想将 foo 复制到 bar。
我试过这个:
bar = class1.foo;
但是当我改变 bar 时, foo 会改变......
我应该怎么办?
注1:所有值的类型为ArrayList<ArrayList<class2>>。
注2:我也试过
public ArrayList<ArrayList<class2>> getFoo(){
return new ArrayList<ArrayList<class2>>(foo);
}
有一个名为 foo 的类 (class0)。
我想将 foo 复制到 bar。
我试过这个:
bar = class1.foo;
但是当我改变 bar 时, foo 会改变......
我应该怎么办?
注1:所有值的类型为ArrayList<ArrayList<class2>>。
注2:我也试过
public ArrayList<ArrayList<class2>> getFoo(){
return new ArrayList<ArrayList<class2>>(foo);
}
如果
new ArrayList<ArrayList<class2>>(foo)
没有达到预期的效果,我假设你想要的是一个深拷贝。
最简单的方法是对其进行序列化,然后对其进行反序列化 - 这将适用于所有可序列化的对象,无论其复杂性如何(... 对象集合的集合):
ArrayList<ArrayList<class2>> obj = null;
try {
FastByteArrayOutputStream fbos =
new FastByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(fbos);
out.writeObject(foo);
out.flush();
out.close();
ObjectInputStream in =
new ObjectInputStream(fbos.getInputStream());
obj = (ArrayList<ArrayList<class2>>) in.readObject();
}
catch(IOException e) {
e.printStackTrace();
}
catch(ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return obj;
不过,您必须将 class2 声明为 Serializable。如果这不是一个选项,你必须声明一个特定的方法来迭代 foo 中的所有数组列表,复制它们
new ArrayList<ArrayList<class2>>(foo.get(i));
然后将它们放入生成的 ArrayList 中。
尝试使用复制构造函数。你可以在这里找到一个例子:复制构造函数,重要的部分是:
public final class Galaxy {
private double fMass;
private final String fName;
public Galaxy (double aMass, String aName) {
fMass = aMass;
fName = aName;
}
/**
* Copy constructor.
*/
public Galaxy(Galaxy aGalaxy) {
this(aGalaxy.getMass(), aGalaxy.getName());
//no defensive copies are created here, since
//there are no mutable object fields (String is immutable)
}
}