大侠指点一下怎么clone对象
我用下面的方法clone一个Object[]对象,怎么不行,请大侠赐教,怎么做,最好给点具体的代码,谢谢了。.分没有了
public class ClassroomContainer implements IClassroomContainer, Cloneable {
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
}
for (int b = 0; b < buildingOfClassrooms.size(); b++) {
Object[] classroom = (Object[]) buildingOfClassrooms.get(b);
Object[] newClassroom = (Object[]) classroom.clone();
}
....
}
------解决方案--------------------Object[] 这是复制一个对象数组啊,你不能单独的复制吗?
------解决方案--------------------这个问题值得思考,以前我也没碰到这样的问题,也希望高手解答下
------解决方案--------------------public Object objectClone() {
Object clone = null;
ByteArrayOutputStream output = new ByteArrayOutputStream(200);
try {
ObjectOutput writer = new ObjectOutputStream(output);
writer.writeObject(this);
writer.close();
} catch (
IOException e) {
System.err.println( "Class not found: " + e);
}
InputStream input = new ByteArrayInputStream(output.toByteArray());
try {
ObjectInput reader = new ObjectInputStream(input);
clone = (Object) reader.readObject();
} catch (IOException e) {
System.err.println(e.toString());
} catch (
ClassNotFoundException e) {
System.err.println( "Class not found: " + e);
}
return clone;
}
------解决方案--------------------楼上说的对,注意复制的对象,还有它的引用对象必须序列化。否则报异常。