[jdom-interest] Bug in Element.getChildren().listIterator(pos)
Paul Cantrell
cantrell at pobox.com
Sun Aug 24 00:00:57 PDT 2003
Working on Macker (at http://innig.net/macker if you're curious), I
found a bug in the listIterator(int) method of the list returned by
Element.getChildren().
The following code demonstrates the bug -- it incorrectly generates a
ClassCastException if element contains text content after its last
child element:
List children = element.getChildren();
for(ListIterator childIter =
children.listIterator(children.size()); childIter.hasPrevious(); )
{
Element subElem = (Element) childIter.previous();
.......
}
The exception occurs because the call to childIter.previous()
erroneously returns a Text object the first time it is called.
The problem appears to be in the last line
ContentList.java.initializeCursor(int start), which is
ContentList.java:1277 in the nightly I just picked up. The final
return incorrectly presumes that the last element in the list matches
the filter. The method *should* go something like this:
private int initializeCursor(int start) {
if (start < 0) {
throw new IndexOutOfBoundsException("Index: " + start);
}
int count = 0;
int lastMatchPos = -1; // <---------
for (int i = 0; i < ContentList.this.size(); i++) {
Object obj = ContentList.this.get(i);
if (filter.matches(obj)) {
lastMatchPos = i; // <----------
if (start == count) {
return i;
}
count++;
}
}
if (start > count) {
throw new IndexOutOfBoundsException("Index: " + start +
" Size: " + count);
}
return lastMatchPos + 1; // <---------
}
WARNING: I haven't tested this patch -- I just typed it straight into
the email. (Sorry!) I hope it's not too far off the mark.
Cheers,
Paul
More information about the jdom-interest
mailing list