Comments below
On 8/8/07, Jukka Zitting <[EMAIL PROTECTED]> wrote:
>
> Hi,
>
> On 8/8/07, Amir Mistric <[EMAIL PROTECTED]> wrote:
> > - What is the *best* way to find out if a child node is the last child
> of its
> > parent (based on certain node type)?
> > - Is there an API that already does this or would I have to create my
> > own method.
> > - If I have to create my own method, what would you recommend?
> > Do an Xpath query using last() or get a count of children and compare
> > last child node with passed in one?
>
> JCR doesn't have methods like Node.getNext() or Node.getPrevious()
> that would allow you to do sideways traversal.
>
> I guess the best way to achieve your goal would be:
>
> Node node = ...
> NodeIterator iterator = node.getParent().getNodes();
> while (iterator.hasNext()) {
> if (node.isSame(iterator.nextNode())) {
> if (iterator.hasNext()) {
> return /* this is not the last sibling */;
> } else {
> return /* this is the last sibling */;
> }
> }
> }
>
> This approach is obviously not too efficient, but can be used to
> implement your use case as well as the "next"/"previous" links
> discussed in another post a while ago.
>
> Perhaps we should ask for JSR 283 to consider adding support for
> sibling access methods?
>
> BR,
>
> Jukka Zitting
Why not do something like
Node node = ...
NodeIterator iterator = node.getParent().getNodes();
long numSibs = iterator.getSize();
iterator.skip(numSibs-1);
if (node.isSame(iterator.nextNode())) {
return /* this is the last sibling */;
} else {
return /* this is not the last sibling */;
}
Even if iterator.skip(n) is no more efficient than n calls of iterator.next(),
it saves a few operations in the body of the while loop.
-Brian