首先你需要注意以下几点
variables= l.clone()
可以通过转换为您的 Vector 来解决编译错误。像这样variables = (Vector<a>)l.clone()
(顺便说一句,忽略类型转换警告)
- 给定的代码
Collections.copy(variables, l);
编译得很好,没有任何错误
- 尝试
Java Naming Conventions
始终使用
Collections.copy()
为您提供收藏的浅表副本。使用以下示例制作您的收藏的深层副本。
- 这里被复制的类应该实现
Cloneable
接口并覆盖clone
方法
- 迭代原始集合并将克隆的对象添加到目标集合
- 该
createCopy
函数返回深度复制的集合
- 注意控制台打印语句中复制向量和原始向量的内存位置的差异
TestCopy
班级_
package com.test;
import java.util.Vector;
public class TestCopy {
private Vector<ClassToCopy> createCopy(Vector<ClassToCopy> classToCopy) {
Vector<ClassToCopy> localVariable = new Vector<ClassToCopy>();
for(ClassToCopy classVar:classToCopy)
try {
localVariable.add((ClassToCopy)classVar.clone());
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return localVariable;
}
public static void main(String[] args) {
Vector<ClassToCopy> originalVector = new Vector<ClassToCopy>();
TestCopy testCopy = new TestCopy();
originalVector.add(new ClassToCopy(1));
originalVector.add(new ClassToCopy(2));
originalVector.add(new ClassToCopy(3));
originalVector.add(new ClassToCopy(4));
System.out.println(originalVector);
Vector<ClassToCopy> copiedVector = testCopy.createCopy(originalVector);
System.out.println(copiedVector);
}
}
ClassToCopy
班级_
package com.test;
public class ClassToCopy implements Cloneable {
private int varA;
/**
* Constructor for ClassToCopy.
* @param varA <tt></tt>
*/
public ClassToCopy() {
this(-1);
}
/**
* Constructor for ClassToCopy.
* @param varA <tt></tt>
*/
public ClassToCopy(int varA) {
super();
this.varA = varA;
}
/**
* Gets the varA.
*
* @return <tt> the varA.</tt>
*/
public int getVarA() {
return varA;
}
/**
* Sets the varA.
*
* @param varA <tt> the varA to set.</tt>
*/
public void setVarA(int varA) {
this.varA = varA;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "ClassToCopy : "+super.toString()+" [varA=" + varA + "]";
}
/* (non-Javadoc)
* @see java.lang.Object#clone()
*/
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
}
我得到的输出
[ClassToCopy : com.test.ClassToCopy@19821f [varA=1], ClassToCopy : com.test.ClassToCopy@addbf1 [varA=2], ClassToCopy : com.test.ClassToCopy@42e816 [varA=3], ClassToCopy : com.test.ClassToCopy@9304b1 [varA=4]]
[ClassToCopy : com.test.ClassToCopy@190d11 [varA=1], ClassToCopy : com.test.ClassToCopy@a90653 [varA=2], ClassToCopy : com.test.ClassToCopy@de6ced [varA=3], ClassToCopy : com.test.ClassToCopy@c17164 [varA=4]]