1、表层克隆
- public class Snake implements Cloneable
- {
- private Snake next;
- private char c;
- Snake(int i, char x){
- c = x;
- if(--i > 0){
- next = new Snake(i,(char)(x+1));
- }
- }
- public void increment(){
- c++;
- if(next!=null){
- next.increment();
- }
- }
- public String toString(){
- String s = ":"+c;
- if(next!=null){
- s += next.toString();
- }
- return s;
- }
- public Object clone(){
- Object o = null;
- try{
- o = super.clone();
- }catch(CloneNotSupportedException e){}
- return o;
- }
- public static void main(String[] args)
- {
- Snake s = new Snake(5,a);
- System.out.println("s ="+s);
- Snake s2 = (Snake)s.clone();
- System.out.println("s2 ="+s2);
- s2.increment();
- System.out.println("after s2.increment, s="+s+" s2 ="+s2);
- }
- }
此时的输出结果:
s =:a:b:c:d:e
after s2.increment, s=:a:c:d:e:f s2 =:b:c:d:e:f
2、深层克隆
- public class Snake implements Cloneable
- {
- private Snake next;
- private char c;
- Snake(int i, char x){
- c = x;
- if(--i > 0){
- next = new Snake(i,(char)(x+1));
- }
- }
- public void increment(){
- c++;
- if(next!=null){
- next.increment();
- }
- }
- public String toString(){
- String s = ":"+c;
- if(next!=null){
- s += next.toString();
- }
- return s;
- }
- public
- <script type="text/java script">BAIDU_CLB_fillSlot("771048");
- 点击复制链接 与好友分享! 回本站首页 <script> function copyToClipBoard(){ var clipBoardContent=document.title + '\r\n' + document.location; clipBoardContent+='\r\n'; window.clipboardData.setData("Text",clipBoardContent); alert("恭喜您!复制成功"); }
<script type="text/java script" id="bdshare_js" data="type=tools&uid=12732"> <script type="text/java script" id="bdshell_js"> <script type="text/java script"> var bds_config = {'snsKey':{'tsina':'2386826374','tqq':'5e544a8fdea646c5a5f3967871346eb8'}}; document.getElementById("bdshell_js").src = "http://bdimg.share.baidu.com/static/js/shell_v2.js cdnversion=" + Math.ceil(new Date()/3600000)