我写了一个类A,如下面的
class A <E> { // class A has objects of E
int x;
private B<T> next // a object of inner class
class B<T> {
// an inner class having objects of type T
T[] elements = (T[]) Object[x];
// has other stuff including many objects
}
public A<E> func ( B<E> val ){
Here I want to clone the value of val so that I can do different operations on other
}
问题出现了,我想写B<E> Temp = B<E>Value.clone()
,其中Value在代码中定义。
但它说克隆不可见。
我该怎么做才能做到这一点......
非常感谢...
答案 0 :(得分:1)
clone()受到保护,因此您只需要在B中重新定义以执行您需要的任何操作。
答案 1 :(得分:0)
最好不要使用clone()
,而是在B
上实现复制构造函数:
class B extends A {
// an inner class having objects of type
List<String> strings = ArrayList<String>();
public B(B that) {
super(that); // call the superclass's copy constructor
this.strings = new ArrayList<String>();
this.strings.add(that.strings);
}
// ...
}
然后致电
public C func ( B val ){
B clone = new B(val);
}
(删除了泛型内容以限制复制构造函数本身的演示)
答案 2 :(得分:0)
以下是Peter的答案示例(未经测试,可能需要一些语法检查):
class A <E> { // class A has objects of E
int x;
private B<T> next // a object of inner class
class B<T> implements Cloneable {
public B<T> clone() {
try {
B<T> klon = (B<T>) super.clone();
// TODO: maybe clone the array too?
return klon;
}
catch(CloneNotSupportedException) {
// should not occur
throw new Error("programmer is stupid");
}
}
// an inner class having objects of type T
T[] elements = (T[]) Object[x];
// has other stuff including many objects
}
public A<E> func ( B<E> val ){
B<E> clone = val.clone();
// more code
}