I got a bad smell from my TreeIterator implementation. It worked and did what it said on the tin (iterated over a Tree) but it didn’t feel right. Turns out, though I’d implemented the syntax for an Iterator I hadn’t implemented the correct semantics. Twas a bit stupid really but basically if, in general you do this
class Iter {
public static void main(String argv[]) {
Vector<integer> ivec = new Vector<integer>();
for(int i=0; i<10; i++) {
ivec.add(new Integer(i));
}
Iterator j = ivec.iterator();
Iterator k = ivec.iterator();
for(int i=0; i<10; i++)
System.out.println("j: " + j.next() + " k:" + k.next());
}
}
the j and k iterators work independantly. The output is
[balor@mowa423-lxajd9 tmp]$ java -cp . Iter
j: 0 k:0
j: 1 k:1
j: 2 k:2
j: 3 k:3
j: 4 k:4
j: 5 k:5
j: 6 k:6
j: 7 k:7
j: 8 k:8
j: 9 k:9
whereas the output for my implementation would have been
[balor@mowa423-lxajd9 tmp]$ java -cp . Iter
j: 0 k:1
j: 2 k:3
j: 4 k:5
j: 6 k:7
j: 8 k:9
So as you can see creating an Iterator works perfectly, however using two Iterators fails disasterously. Given that I had implemented the syntax correctly and my unit tests had passed I thought my code should have been correct. I don’t know what I’m trying to say, but maybe it’s just to underline (again) that semantics is a much higher level of understanding than syntax, but semantic misunderstandings/misinterpretations probably cause more bugs than syntactic proplems which are normally picked up by the compiler.
Anyway….it was a stupid mistake to make.
Hmm, I wouldn’t say it was a stupid mistake. I could see myself making it. I guess I have 2 questions
a) Did you use a static variable?
b) Why are you implementing Iterator, its already there
Good post though.
Yeah I used a static variable. I have a static
List<Model> modelswhich I created a staticIteratorby callingmodels.iterator(). Then myNodeclass which implementsIterablepassed back the staticIteratorwhen anyone called for anIterator.So it was correct syntactically…but not semantically. And as you said, the problem was a static variable.
The reason I implement a
NodeIteratoris that I want to do some processing withmodels.next()before I return theObject. So theNodeIteratornow has a non-static version ofmodelIterator.I think my problem was that I was trying to do everything at once i.e. build a tree structure, iterate over the tree structure and return the right value. If I had taken these things one at a time I wouldn’t have messed up.
testcomment867