KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > python > modules > sets > PySetIterator


1
2 package org.python.modules.sets;
3
4 import org.python.core.PyObject;
5 import org.python.core.Py;
6
7 import java.util.Iterator JavaDoc;
8 import java.util.Set JavaDoc;
9 import java.util.ConcurrentModificationException JavaDoc;
10
11 public class PySetIterator extends PyObject {
12     private Set JavaDoc _set;
13     private int _count;
14     private Iterator JavaDoc _iterator;
15
16     public PySetIterator(Set JavaDoc set) {
17         super();
18         this._set = set;
19         this._count = 0;
20         this._iterator = set.iterator();
21     }
22
23     public PyObject __iter__() {
24         return this;
25     }
26
27     /**
28      * Returns the next item in the iteration or raises a StopIteration.
29      * <p/>
30      * <p/>
31      * This differs from the core Jython Set iterator in that it checks if
32      * the underlying Set changes in size during the course and upon completion
33      * of the iteration. A RuntimeError is raised if the Set ever changes size
34      * or is concurrently modified.
35      * </p>
36      *
37      * @return the next item in the iteration
38      */

39     public PyObject next() {
40         PyObject o = this.__iternext__();
41         if (o == null) {
42             if (this._count != this._set.size()) {
43                 // CPython throws an exception even if you have iterated through the
44
// entire set, this is not true for Java, so check by hand
45
throw Py.RuntimeError("dictionary changed size during iteration");
46             }
47             throw Py.StopIteration("");
48         }
49         return o;
50     }
51
52     /**
53      * Returns the next item in the iteration.
54      *
55      * @return the next item in the iteration
56      * or null to signal the end of the iteration
57      */

58     public PyObject __iternext__() {
59         if (this._iterator.hasNext()) {
60             this._count++;
61             try {
62                 return Py.java2py(this._iterator.next());
63             } catch (ConcurrentModificationException JavaDoc e) {
64                 throw Py.RuntimeError("dictionary changed size during iteration");
65             }
66         }
67         return null;
68     }
69 }
70
Popular Tags