正确增加Cloneable接口
来源:互联网 发布:买家淘宝购物流程 编辑:程序博客网 时间:2024/06/02 21:34
今天调试程序,发现在解析的时候使用了clone函数,但是得到的结果是null,很奇怪。
看代码,override了clone函数,还是得到null。
继续搜索stackoverflow,发现没有增加Cloneable接口声明。
增加声明后,问题解决。
http://stackoverflow.com/questions/1052340/what-is-wrong-with-this-clone
The standard pattern for making a class cloneable is:
- Implement
Cloneable
- Override the
clone()
method and make it public - In
clone()
callsuper.clone()
and then copy any mutable object's state
You should not create a new object using new
. The proper way is to callsuper.clone()
for a new instance. Object
's clone()
is special and will create a new copy of the object and copy its primitive fields and references.
你不需要使用new关键字创建新对象。合适的方法是调用super.clone建立新对象。Object的clone()是特别的,会创建一个新的对象拷贝,以及拷贝它的基本类型和引用。(这里涉及到深拷贝和浅拷贝,请自行glgoo.com)
For example:
public class Person implements Cloneable { protected String name; // Note that overridden clone is public public Object clone() { Person clone = (Person)super.clone(); // No need to copy name as the reference will be // copied by Object's clone and String is immutable return clone; }}public class Employee extends Person { protected int id; protected java.awt.Point location; public Object clone() { Employee clone = (Employee )super.clone(); // No need to copy id as Object's clone has already copied it // Need to clone location as Point is mutable and could change clone.location = location.clone(); return clone; }}
0 0
- 正确增加Cloneable接口
- cloneable接口
- Cloneable接口
- Cloneable 接口
- Cloneable接口
- Cloneable接口
- cloneable接口
- Cloneable接口分析
- java.lang.Cloneable接口
- Java中Cloneable接口
- Java中Cloneable接口
- Java中Cloneable接口
- Java中Cloneable接口
- Cloneable接口分析
- Cloneable接口使用
- Cloneable接口实例
- java中Cloneable接口
- Java中Cloneable接口
- 遇到的多条件贝叶斯概率问题
- 使用方法拦截器MethodInterceptor和AOP统一处理log
- 阶与原根学习笔记
- LeetCode 226 Invert Binary Tree
- css sprite的实现
- 正确增加Cloneable接口
- uva10820(简单数学题)
- partition-list
- apache2.4 以上的版本,cgi-bin中的文件不能运行。
- ios tableView性能优化策略
- 我也开博客了……
- 非你莫属 周倩如 女程序员 神一样的选手!
- maven编译代码详细介绍
- 抢测试1