1 33 package net.sf.jga.util; 34 35 import java.lang.reflect.Array ; 36 import java.util.ArrayList ; 37 import java.util.NoSuchElementException ; 38 import java.util.Iterator ; 39 40 47 48 public class CachingIterator<T> implements Iterator <T>, Iterable <T> { 49 private Iterator <? extends T> _base; 51 52 private Object [] _cache; 54 55 private int _baseptr = 0; 58 59 private int _cnt = 0; 61 62 private int _size; 64 65 68 69 public CachingIterator (Iterator <? extends T> base) { 70 this(base, 1); 71 } 72 73 78 79 public CachingIterator (Iterator <? extends T> base, int max) { 80 if (max <= 0) 81 throw new IllegalArgumentException (); 82 83 _base = (base != null) ? base : new EmptyIterator<T>(); 84 _size = max; 85 86 _cache = new Object [_size]; 87 } 88 89 93 94 public boolean hasCached(int n) { 95 return n > 0 && n <= _cnt; 96 } 97 98 101 102 public T cached(int n) { 103 if (n <= 0 || n > _cnt || n > _size) 104 throw new NoSuchElementException (); 105 106 111 return (T) _cache[(_baseptr +_size - n) % _size]; 112 } 113 114 117 public int getCacheSize() { 118 return _size; 119 } 120 121 124 public int getCacheCount() { 125 return _cnt; 126 } 127 128 132 public Iterator <T> iterator() { return this; } 133 134 138 public boolean hasNext() { 139 return _base.hasNext(); 140 } 141 142 public T next() { 143 if (_cnt < _size) 144 ++_cnt; 145 146 int n = _baseptr; 147 _baseptr = ++_baseptr % _size; 148 _cache[n] =_base.next(); 149 150 155 return (T) _cache[n]; 156 } 157 158 159 166 public void remove() { 167 _base.remove(); 168 } 169 } 170 | Popular Tags |