KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sleepycat > je > tree > TreeIterator


1 /*-
2  * See the file LICENSE for redistribution information.
3  *
4  * Copyright (c) 2002,2006 Oracle. All rights reserved.
5  *
6  * $Id: TreeIterator.java,v 1.23 2006/10/30 21:14:26 bostic Exp $
7  */

8
9 package com.sleepycat.je.tree;
10
11 import java.util.Iterator JavaDoc;
12 import java.util.NoSuchElementException JavaDoc;
13
14 import com.sleepycat.je.DatabaseException;
15 import com.sleepycat.je.latch.LatchNotHeldException;
16
17 /**
18  * TreeIterator implements an Iterator over Tree's. Not protected
19  * against insertions like cursors.
20  */

21 public final class TreeIterator implements Iterator JavaDoc {
22     private Tree tree;
23     private BIN nextBin;
24     private int index;
25
26     public TreeIterator(Tree tree)
27     throws DatabaseException {
28
29     nextBin = (BIN) tree.getFirstNode();
30     if (nextBin != null) {
31         nextBin.releaseLatch();
32     }
33     index = -1;
34     this.tree = tree;
35     }
36
37     public boolean hasNext() {
38     boolean ret = false;
39         try {
40             if (nextBin != null) {
41                 nextBin.latch();
42             }
43             advance();
44             ret = (nextBin != null) && (index < nextBin.getNEntries());
45         } catch (DatabaseException e) {
46             // eat exception
47
} finally {
48             try {
49                 if (nextBin != null) {
50                     nextBin.releaseLatch();
51                 }
52             } catch (LatchNotHeldException e) {
53         /* Klockwork - ok */
54             }
55         }
56         return ret;
57     }
58
59     public Object JavaDoc next() {
60
61         Object JavaDoc ret = null;
62         try {
63             if (nextBin == null) {
64                 throw new NoSuchElementException JavaDoc();
65             }
66             nextBin.latch();
67             ret = nextBin.getKey(index);
68         } catch (DatabaseException e) {
69         // eat exception, return null;
70
} finally {
71             try {
72                 if (nextBin != null) {
73                     nextBin.releaseLatch();
74                 }
75             } catch (LatchNotHeldException e) {
76         /* Klockwork - ok */
77             }
78         }
79     return ret;
80     }
81
82     public void remove() {
83     throw new UnsupportedOperationException JavaDoc();
84     }
85
86     private void advance()
87     throws DatabaseException {
88
89     while (nextBin != null) {
90         if (++index < nextBin.getNEntries()) {
91         return;
92         }
93         nextBin = tree.getNextBin(nextBin, false /* traverseWithinDupTree */);
94         index = -1;
95     }
96     }
97 }
98
Popular Tags