1 package org.tigris.scarab.util; 2 3 48 49 import java.util.Collections ; 50 import java.util.Iterator ; 51 import java.util.NoSuchElementException ; 52 53 public class SubsetIterator 54 implements Iterator 55 { 56 public static final SubsetIterator EMPTY = new EmptySubsetIterator(); 57 58 private Iterator i; 59 private final int offset; 60 private final int elements; 61 private int currentPosition; 62 63 72 public SubsetIterator(Iterator i, int offset, int elements) 73 { 74 75 this.i = i; 76 this.offset = offset; 77 this.elements = elements; 78 currentPosition = 0; 79 } 80 81 89 public SubsetIterator(Iterator i, int offset) 90 { 91 this(i, offset, Integer.MAX_VALUE); 92 } 93 94 private Boolean hasNext; 95 public boolean hasNext() 96 { 97 if (hasNext == null) 98 { 99 hasNext = (internalIterate()) 100 ? Boolean.TRUE : Boolean.FALSE; 101 } 102 return hasNext.booleanValue(); 103 } 104 105 boolean firstCall = true; 106 private boolean internalIterate() 107 { 108 if (firstCall) 109 { 110 for (int m = 0; i.hasNext() && m < offset; m++) 111 { 112 i.next(); 113 } 114 firstCall = false; 115 } 116 currentPosition++; 117 return i.hasNext() && currentPosition <= elements; 118 } 119 120 public Object next() 121 { 122 if (hasNext()) 123 { 124 hasNext = null; 125 return i.next(); 126 } 127 else 128 { 129 throw new NoSuchElementException ("Iterator is exhausted"); } 131 } 132 133 public void remove() 134 { 135 i.remove(); 136 } 137 138 } 139 140 class EmptySubsetIterator extends SubsetIterator 141 { 142 EmptySubsetIterator() 143 { 144 super(Collections.EMPTY_SET.iterator(), 0, 0); 145 } 146 147 public boolean hasNext() 148 { 149 return false; 150 } 151 152 public Object next() 153 { 154 throw new NoSuchElementException ("This is an empty list."); } 156 157 public void remove() 158 { 159 throw new IllegalStateException ("next() will throw exception, it is " 160 + "not possible to call this method."); } 162 } 163 | Popular Tags |