[jdom-interest] Merging text nodes

Alex Rosen arosen at silverstream.com
Tue Feb 19 08:19:22 PST 2002


I never thought that merging text nodes under the covers was a particularly
important feature. It probably wouldn't happen very often; it adds
complexity to the code; and anyone that actually cares can just do it
themselves.

> The kicker is add(int,Object),
> for example
>
>     element.addContent( new Element("e1"));          // index = 0
>     element.addContent( new Text("This is a test")); // index = 1
>     element.addContent( new Element("e2"));          // index = 2
>     List list = element.getContent();
>     list = element.add(2, new Text(", only a test");
>
> with Text nodes merged then list.get(2) yields e2 instead of a Text node.
> But I can live with that if others can.

I think this might be a problem... suppose you were iterating over the
children, adding or removing nodes? Presumably set() and remove() would also
merge newly-adjacent text nodes, which could cause the following (weird, but
legal) code to fail:

List content = element.getContent();
int count = content.size();
for (int i = 0; i < count; i++)
  content.set(i, "text");

It also violates the contract of the List interface: the JavaDoc for
add(int, Object) says "Shifts the element currently at that position (if
any) and any subsequent elements to the right (adds one to their indices)."
And similarly for remove(int).

Alex Rosen
alex at silverstream.com




More information about the jdom-interest mailing list