J
Joris Bleys
Hi there,
I have troubles implementing a deep cloning for a general container class.
I want to be able to contain any possible Object inside a self-created
class SetList. The container I'm using now is java.util.LinkedList. This
LinkedList supports shallow cloning.
When the cloning method is called I would like to do a conditional
cloning:
- if all instances of objects inside the containerclas are cloneable,
clone them
- if one of them is not, throw an exception
I got this idea from a book "Thinking in Java", but I don't know how to
implement it. Here's what I got so far:
public SetList duplicate() {
SetList duplicateSetList = new SetList(); Iterator i =
this.iterator();
while (i.hasNext()) {
A-> duplicateSetList.add(i.next().clone());
}
return duplicateSetList;
}
}
This method is called duplicate(), because my teacher doesn't like any
downcasts, so this returns a SetList. In my humble opinion, I should
follow the Java Conventions and implement the Clone method, but we're
still in discussion.
Bu the real problem is at A. i.next() returns an Object, and somehow this
has to be upcasted to its real type. Does anyone know how this can be done
cleanly ?
I am aware of the serialize-method for deepcloning, but I think it's quite
nasty.
I thought one of you guys/girls could help me out .
Thanks in advance.
I have troubles implementing a deep cloning for a general container class.
I want to be able to contain any possible Object inside a self-created
class SetList. The container I'm using now is java.util.LinkedList. This
LinkedList supports shallow cloning.
When the cloning method is called I would like to do a conditional
cloning:
- if all instances of objects inside the containerclas are cloneable,
clone them
- if one of them is not, throw an exception
I got this idea from a book "Thinking in Java", but I don't know how to
implement it. Here's what I got so far:
public SetList duplicate() {
SetList duplicateSetList = new SetList(); Iterator i =
this.iterator();
while (i.hasNext()) {
A-> duplicateSetList.add(i.next().clone());
}
return duplicateSetList;
}
}
This method is called duplicate(), because my teacher doesn't like any
downcasts, so this returns a SetList. In my humble opinion, I should
follow the Java Conventions and implement the Clone method, but we're
still in discussion.
Bu the real problem is at A. i.next() returns an Object, and somehow this
has to be upcasted to its real type. Does anyone know how this can be done
cleanly ?
I am aware of the serialize-method for deepcloning, but I think it's quite
nasty.
I thought one of you guys/girls could help me out .
Thanks in advance.