Java Mailing List Archive

http://www.junlu.com/

Home » Home (12/2007) » JDOM User »

[jdom-interest] Element.clone() - code questions

Victor Toni

2004-11-26

Replies:

I was browsing the code to see what happens if Element.clone() gets called.

The clone method has this snippets:

-----------
...

// Cloning additional namespaces
if (additionalNamespaces != null) {
  int additionalSize = additionalNamespaces.size();
  element.additionalNamespaces = new ArrayList(additionalSize);
  for (int i = 0; i < additionalSize; i++) {
    Object additional = additionalNamespaces.get(i);
    element.additionalNamespaces.add(additional);
  }
}

...
// cloning content
...

// Handle additional namespaces
if (additionalNamespaces != null) {
  // Avoid additionalNamespaces.clone() because List isn't Cloneable
  element.additionalNamespaces = new ArrayList();
  element.additionalNamespaces.addAll(additionalNamespaces);
}

-----------

Maybe I'm missing something but shouldn't this code be executed only once?
I changed the clone method to the code below and it still works (or
seems to :)

------------------------
  public Object clone() {

    // Ken Rune Helland <kenh@(protected)

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

    // name and namespace are references to immutable objects
    // so super.clone() handles them ok

    // Reference to parent is copied by super.clone()
    // (Object.clone()) so we have to remove it
    // Actually, super is a Content, which has already detached in the
    // clone().
    // element.parent = null;

    // Reference to content list and attribute lists are copyed by
    // super.clone() so we set it new lists if the original had lists
    element.content = new ContentList(element);
    element.attributes = new AttributeList(element);

    // Cloning attributes
    if ( attributes != null ) {
       for( int i = 0; i < attributes.size(); i++ ) {
          final Attribute attribute = (Attribute) attributes.get(i);
          element.attributes.add(attribute.clone());
       }
    }

    // Cloning additional namespaces
    if ( additionalNamespaces != null ) {
       element.additionalNamespaces = new
ArrayList(additionalNamespaces);
    }

    // Cloning content
    if ( content != null ) {
       for( int i = 0; i < content.size(); i++ ) {
          final Content c = (Content) content.get(i);
          element.content.add(c.clone());
       }
    }

    return element;
  }

------------------------


Kindest regards,
Victor
_______________________________________________
To control your jdom-interest membership:
http://www.jdom.org/mailman/options/jdom-interest/youraddr@(protected)
©2008 junlu.com - Jax Systems, LLC, U.S.A.