复制对象
我试图复制一个对象但没有成功。我尝试过
- 序列化
- 克隆
这两种方法都不适合我。
当我使用序列化时(我使用此处指定的技术 更快的深层副本Java 对象)我得到了NullPointerException
。通过克隆,我获得了原始对象引用。
场景是:
我有一个带有数据 char[][] board
的抽象类 A 和一个扩展类 B
。我想复制数据 board
为此我在 B
中实现了两个方法 - getboard()
和 setboard()
> 并实现了一个克隆方法,
B b1 = new B;
B.initialize();
B b2 new B;
B2 = B1.clone(B2)
但是这不起作用。任何帮助将不胜感激。
谢谢:-)
public B clone() {
B N = new B();
try {
N = (B)super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
N.setBoard(this.getBoard());
return N;
}
关于序列化,反序列化后,当我尝试绘制板时,它给了我NullPointerException
。我的结论是,反序列化无法正常工作。
I am trying to duplicate an object with no success. I tried
- Serialization
- Cloning
both methods don't work for me.
When I used serialization (I am using the technique specified here Faster Deep Copies of Java Objects) I got NullPointerException
. With cloning I got original object reference.
Scenario is:
I have one abstract class A with data char[][] board
and an extended class B
. I want to duplicate the data board
for this I implemented two methods in B
- getboard()
and setboard()
and implemented a clone method such that
B b1 = new B;
B.initialize();
B b2 new B;
B2 = B1.clone(B2)
But this is not working. Any help would be appreciated.
Thanks :-)
public B clone() {
B N = new B();
try {
N = (B)super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
N.setBoard(this.getBoard());
return N;
}
Regarding the serialization, after deserializing when i try to draw the board it is giving me NullPointerException
. I conclude that, deserialization didn't work properly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
覆盖
B
中的clone
方法:并使用它来创建重复项:
更新:
尝试以下操作(假设
B
> 实现Cloneable
):更新:
board
的自定义实现:Override the
clone
method inB
:And use it to create duplicate:
Update:
Try the following (assuming that
B
implementsCloneable
):Update:
Custom implementation for
board
:随着时间的推移,我发现使用第三方库进行对象克隆可以成为救星。我推荐的项目之一是“Cloning”,可在 http://code.google.com 上找到/p/cloning/
这是一个示例:
Over the time I have found out that using a third party library to do object cloning can be a life saver. One of the projects I'd recommend is "Cloning", available at http://code.google.com/p/cloning/
Here's an example: