01: /*
02: * Javolution - Java(TM) Solution for Real-Time and Embedded Systems
03: * Copyright (C) 2006 - Javolution (http://javolution.org/)
04: * All rights reserved.
05: *
06: * Permission to use, copy, modify, and distribute this software is
07: * freely granted, provided that this notice is preserved.
08: */
09: package javolution.util;
10:
11: import j2me.lang.IllegalStateException;
12: import j2me.util.Iterator;
13: import j2me.util.NoSuchElementException;
14: import javolution.context.ObjectFactory;
15: import javolution.util.FastCollection.Record;
16:
17: /**
18: * <p> This class represents an iterator over a {@link Fastcollection).
19: * Iterations are thread-safe if the collections records are not removed
20: * or inserted at arbitrary position (appending/prepending is fine).</p>
21: *
22: * <p> Iterators are allocated on the stack when executing in a
23: * {@link StackContext javolution.context.StackContext}.</p>
24: *
25: * @author <a href="mailto:jean-marie@dautelle.com">Jean-Marie Dautelle</a>
26: * @version 3.7, March 17, 2005
27: */
28: final class FastIterator implements Iterator {
29:
30: private static final ObjectFactory FACTORY = new ObjectFactory() {
31: protected Object create() {
32: return new FastIterator();
33: }
34:
35: protected void cleanup(Object obj) {
36: FastIterator iterator = (FastIterator) obj;
37: iterator._collection = null;
38: iterator._current = null;
39: iterator._next = null;
40: iterator._tail = null;
41: }
42: };
43:
44: private FastCollection _collection;
45:
46: private Record _current;
47:
48: private Record _next;
49:
50: private Record _tail;
51:
52: public static FastIterator valueOf(FastCollection collection) {
53: FastIterator iterator = (FastIterator) FastIterator.FACTORY
54: .object();
55: iterator._collection = collection;
56: iterator._next = collection.head().getNext();
57: iterator._tail = collection.tail();
58: return iterator;
59: }
60:
61: private FastIterator() {
62: }
63:
64: public boolean hasNext() {
65: return (_next != _tail);
66: }
67:
68: public Object next() {
69: if (_next == _tail)
70: throw new NoSuchElementException();
71: _current = _next;
72: _next = _next.getNext();
73: return _collection.valueOf(_current);
74: }
75:
76: public void remove() {
77: if (_current != null) {
78: // Uses the previous record (not affected by the remove)
79: // to set the next record.
80: final Record previous = _current.getPrevious();
81: _collection.delete(_current);
82: _current = null;
83: _next = previous.getNext();
84: } else {
85: throw new IllegalStateException();
86: }
87: }
88: }
|