deep cloning for containerclass (consistent)

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.
 
T

Tim Tyler

: I am aware of the serialize-method for deepcloning, but I think it's quite
: nasty.

....but... it's beautiful!

You Never Have To Write A Deep Clone Again[TM].
 
T

Tim Tyler

: On Wed, 06 Aug 2003 13:46:07 +0000, Tim Tyler wrote:

:> : I am aware of the serialize-method for deepcloning, but I think it's quite
:> : nasty.
:>
:> ...but... it's beautiful!
:>
:> You Never Have To Write A Deep Clone Again[TM].

: I think it is using Serializing for something it was never meant to.

: But that's a matter of taste :)

Sure - but let's not forget that - if you start using it -
You Never Have To Write A Deep Clone Again[*].

Just think of all those errors where you forget to deep clone some
field - or add a field and then forget to update your clone method.

[*] Subject to terms and condititons - the resulting programs
may not execute at absoultely the maximum possible top speed.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,813
Latest member
lawrwtwinkle111

Latest Threads

Top