I'm attempting to make a Java class that emulates a Jython list, with some
special conditions to it.
I have a java class called an Array, which contains a collection of another
Java class called an Element.
I then have a Jython script set up so I can do the following:
arr[pos]
where arr is the Java Array object, and pos is the index in that Array
object, the returned value will be the Element object.
Now, to my problem... I am unable to get an iterator to work correctly. What
I mean is this code:
for val in arr:
count[val] += 1
Doesn't work. I get the following:
java.lang.NoSuchElementException()
Mind you, this method does work:
for pos in range(len(arr)):
count[arr[pos]] += 1
But the former is far cleaner than the latter, especially given Python's *
for* syntax.
I took a look at the Jython 2.5.1 javadoc, which says to set up the
__iternext__() method for my iterator, and I looked at the Python 2.5
documentation to see that there should be a next() method defined. In both
cases, a null should be sent if there is no more elements to iterate over.
My iterator looks like this:
/**
* A forward-facing iterator for the Array.
*
* @author darkhelm
*/
public class Iter implements Iterator<Element> {
/**
* The actual iterator, able to go forward or backward.
*/
private ListIterator<Element> iter = arr.listIterator();
/**
* @return the actual iterator that is used.
*/
protected ListIterator<Element> getIter() {
return iter;
}
/* (non-Javadoc)
* @see java.util.Iterator#hasNext()
*/
@Override
public boolean hasNext() {
return getIter().hasNext();
}
/* (non-Javadoc)
* @see java.util.Iterator#next()
*/
@Override
public Element next() {
try {
return getIter().next();
} catch(NoSuchElementException e) {
return null;
}
}
/**
* @return the next element from the iterator.
*/
public Element __iternext__() {
return next();
}
/* (non-Javadoc)
* @see java.util.Iterator#remove()
*/
@Override
public void remove() {
getIter().remove();
}
}
This produces the above "NoSuchElementException" exception being thrown when
I do the first for loop I mentioned.
If I modify next() method as below:
public Element next() {
try {
return getIter().next();
} catch(NoSuchElementException e) {
return null;
}
}
And then I run the first for loop, it changes the exception to a
java.lang.NullPointerException(). This suggests to me that there is some
other way to notify Jython that the iterator has reached the end. Because
everything I've seen says that if it returns null, it should stop. Then
again, for Java, the NoSuchElementException() exception should also stop the
iterator, shouldn't it?
Anyway, I'd appreciate some help or at least a nod in the right direction
for me to get this working. Thanks.
--
"I'm not responcabel fer my computer's spleling errnors" - Xlorep DarkHelm
Website: http://darkhelm.org
Sent from Santa Maria, California, United States