[jdom-interest] bug in PartialList addAll method?
Mika Haapakorpi
mika.haapakorpi at sensor-sc.fi
Mon Jun 18 10:05:21 PDT 2001
Bug?
------------
The following piece of code throws a java.util.NoSuchElementException
Element e = new Element("koe");
List v = new Vector();
v.add(new Element("koe1"));
v.add(new Element("koe2"));
e.getChildren().addAll(v);
List v2 = new Vector();
v2.add(new Element("koe1"));
v2.add(new Element("koe2"));
e.getChildren("koe").addAll(v2); <- exception thrown from this line:
stacktrace:
Exception in thread "main" java.util.NoSuchElementException
at java.util.LinkedList.getLast(LinkedList.java:109)
at org.jdom.PartialList.addAll(PartialList.java:248)
at SAXBuilderDemo.main(SAXBuilderDemo.java:215)
I'm using todays' snapshot of jdom; 18.6.2001
----------
Fixing?
----------
The reason for this seems quite obvious as we can see from the source of PartialList:
public boolean addAll(Collection c) {
if (backingList.isEmpty()) {
return addAll(0, c);
} else {
return addAll(backingList.indexOf(getLast()) + 1, c);
}
}
if this PartialList is empty and backing list is not the getLast method will throw it.
I tried this simple fix which seem to be obvious solution also solving some other problems of addAll:
public boolean addAll(Collection c) {
// XXX What if the element already has a parent?
for (Iterator i = c.iterator(); i.hasNext(); ) {
Object o = i.next();
if (o instanceof Element) {
((Element)o).setParent(parent); // null is OK
}
}
if (backingList.isEmpty() || this.isEmpty()) {
return (backingList.addAll(c) && super.addAll(c));
} else {
return ( backingList.addAll(backingList.indexOf(this.getLast()) + 1, c) &&
super.addAll(c) );
}
}
but the result was unexpected: it did not throw any exception but the element e looked like this:
<koe><koe1 /><koe2 /><koe1 /><koe2 /><koe1 /><koe2 /><koe1 /><koe2 /><koe1 /><koe2 /></koe>
instead of 4 subelements there was 10 of them ???????
Now i'm using this:
public boolean addAll(Collection c) {
Iterator i = c.iterator();
boolean value = true;
while(i.hasNext() && value ) value = this.add(i.next());
return value;
}
This fix seems to work but of course all the elements are always added to the end of the entire content of e not after the last element in PartialList (like it should be ... ?)
Mika Haapakorpi
Sensor Software Consulting
mika.haapakorpi at sensor-sc.fi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://jdom.org/pipermail/jdom-interest/attachments/20010618/2fa0e35f/attachment.htm
More information about the jdom-interest
mailing list