[jdom-interest] clone() and subclassing (obs forgot some lines)

Ken Rune Helland kenh at csc.no
Thu Mar 1 09:04:57 PST 2001


I have a suggjestion about clone()

for example in Element.clone() the first line
shoud be

Element element = (Element) super.clone();

instead of

Element element = new Element(name, namespace);

This way in my subclass i can call

MyElementSubClass element = (MyElementSubClass) super.clone();

and get a MyElementSubClass object where all the Element stuff
is already set correctly and only care about my added stuff.

This shoud also apply to the other classes.

Object.clone() makes a byte for byte copy so
you will only need to care about references to
mutable objects
( clone.foobar = (this.foobar == null)?null:(Foobar) this.foobar.clone() );

My suggjesgstion for Element.clone():

      * <p>
      *  This returns a deep clone of this element.
      *  The new element is detached from its parent, and getParent()
      *  on the clone will return null.
      * </p>
      * @return the clone of this element
     public Object clone() {
         Element element = (Element) super.clone(); // will return an 
                                                    // or a supclass of Element

	// no need to worry anbout name and namespace
	// they are imutable and the references will be
	// copied by Object.clone

	// these must be set to null because they
	// are copied by Object.clone() and the clone is not to belong to a
	// document or parent yet;
	element.parent == null;
	element.Document == null;

	// the clone also has references to the originals list
	// so this must be set to null befor we add the cloned
	// content (new lists will be created by the add metods)
	element.attributes = null;
	element.content = null;
	element.additionalNamespaces = null;
         if (attributes != null) {
             // List list = new LinkedList(); // i did not se the point of 
this line
             for (Iterator i = attributes.iterator(); i.hasNext(); ) {

         if (content != null) {
             for (Iterator i = content.iterator(); i.hasNext(); ) {
                 Object obj = i.next();
                 if (obj instanceof String) {
                 } else if (obj instanceof Comment) {
                 } else if (obj instanceof Entity) {
                 } else if (obj instanceof Element) {
                 } else if (obj instanceof CDATA) {

	// Handle additional namespaces
         if (additionalNamespaces != null) {
             element.additionalNamespaces =
                 (LinkedList) additionalNamespaces.clone();

         return element;

I think this could also be done on the other clonable classes.

Am i missing somting that would invalidate my reasoning?

Best Regards

More information about the jdom-interest mailing list