java vactor clone_如何用Java中的Vector进行深层复制

下面让我们复习一下本章早些时候提出的Vector例子。这一次Int2类是可以克隆的,所以能对Vector进行深层复制:

58069c557fa8657e1a6e32c9a060b6b2.png

//: AddingClone.java

// You must go through a few gyrations to

// add cloning to your own class.

import java.util.*;

class Int2 implements Cloneable {

private int i;

public Int2(int ii) { i = ii; }

public void increment() { i++; }

public String toString() {

return Integer.toString(i);

}

public Object clone() {

Object o = null;

try {

o = super.clone();

} catch (CloneNotSupportedException e) {

System.out.println("Int2 can't clone");

}

return o;

}

}

// Once it's cloneable, inheritance

// doesn't remove cloneability:

class Int3 extends Int2 {

private int j; // Automatically duplicated

public Int3(int i) { super(i); }

}

public class AddingClone {

public static void main(String[] args) {

Int2 x = new Int2(10);

Int2 x2 = (Int2)x.clone();

x2.increment();

System.out.println(

"x = " + x + ", x2 = " + x2);

// Anything inherited is also cloneable:

Int3 x3 = new Int3(7);

x3 = (Int3)x3.clone();

Vector v = new Vector();

for(int i = 0; i < 10; i++ )

v.addElement(new Int2(i));

System.out.println("v: " + v);

Vector v2 = (Vector)v.clone();

// Now clone each element:

for(int i = 0; i < v.size(); i++)

v2.setElementAt(

((Int2)v2.elementAt(i)).clone(), i);

// Increment all v2's elements:

for(Enumeration e = v2.elements();

e.hasMoreElements(); )

((Int2)e.nextElement()).increment();

// See if it changed v's elements:

System.out.println("v: " + v);

System.out.println("v2: " + v2);

}

} ///:~

Int3自Int2继承而来,并添加了一个新的基本类型成员int j。大家也许认为自己需要再次覆盖clone(),以确保j得到复制,但实情并非如此。将Int2的clone()当作Int3的clone()调用时,它会调用Object.clone(),判断出当前操作的是Int3,并复制Int3内的所有二进制位。只要没有新增需要克隆的句柄,对Object.clone()的一个调用就能完成所有必要的复制——无论clone()是在层次结构多深的一级定义的。

至此,大家可以总结出对Vector进行深层复制的先决条件:在克隆了Vector后,必须在其中遍历,并克隆由Vector指向的每个对象。为了对Hashtable(散列表)进行深层复制,也必须采取类似的处理。

这个例子剩余的部分显示出克隆已实际进行——证据就是在克隆了对象以后,可以自由改变它,而原来那个对象不受任何影响。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值