java clone 深度问题(final 对象clone)

hzhxxx hzhxxx 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

//import java.util.*;

public class TestClone implements java.lang.Cloneable {
private final String m_s = "SSSS";
private final String m_t;
private final String[] m_a;

TestClone()
{
m_t = "init TestClone";
m_a = new String[2];
m_a[0] = m_s;
m_a[1] = m_t;
}

public <T> void out(T s)
{
System.out.println(s);
}

protected TestClone clone()
{
TestClone nobj = null;
try
{
nobj = (TestClone)super.clone();
//问题在这里被提出了,final 导致 m_a 不能被 clone
//nobj.m_a = this.m_a.clone();

}
catch(java.lang.CloneNotSupportedException e)
{
//throw new
}
return nobj;
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

TestClone test1 = new TestClone();
test1.out(test1.m_s);
test1.out(test1.m_t);

TestClone test2 = test1.clone();
test2.out(test2.m_s);
test2.out(test2.m_t);
//1. 这里有一个问题,按道理 test2 没有调用 构造函数 TestClone,那
//m_a 对象应该没有实例化,访问应该报错
//2.问题在这里被提出了,final 导致 m_a 不能被 clone ,导致所有的对象只能共享一个区间
//如果是确定这样,没有问题(比如 m_a 存储的就是一组常量)
test1.m_a[0] = "dddddddoooo";
test2.out(test2.m_a.length);
test2.out(test2.m_a[0]);
test2.out(test2.m_a[1]);
}

}
...全文

相关推荐

评论 4
收藏 已收藏
分享
返回顶部
hzhxxx
Java SE 62,621 成员 307,251 内容