J
Joris Bleys
Ok, I'm not putting up a consistent story, let me try to correct myself.
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
containerclass SetList.
SetList uses an internal datastructure to keep all objects together. For
now I'm using java.util.LinkedList which only supports shallow cloning. :/
When the cloning method is called I would like to do a conditional
cloning:
- if all objects inside the containerclas are instances of cloneable
classes, 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.
But the real problem is at A. i.next() returns an Object, and somehow this
has to be upcasted to its real type. This is because Object.clone() is
protected. 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
containerclass SetList.
SetList uses an internal datastructure to keep all objects together. For
now I'm using java.util.LinkedList which only supports shallow cloning. :/
When the cloning method is called I would like to do a conditional
cloning:
- if all objects inside the containerclas are instances of cloneable
classes, 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.
But the real problem is at A. i.next() returns an Object, and somehow this
has to be upcasted to its real type. This is because Object.clone() is
protected. 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.