1 16 package org.apache.commons.collections.iterators; 17 18 import java.lang.reflect.Array ; 19 import java.util.NoSuchElementException ; 20 21 import org.apache.commons.collections.ResettableIterator; 22 23 43 public class ArrayIterator implements ResettableIterator { 44 45 46 protected Object array; 47 48 protected int startIndex = 0; 49 50 protected int endIndex = 0; 51 52 protected int index = 0; 53 54 62 public ArrayIterator() { 63 super(); 64 } 65 66 74 public ArrayIterator(final Object array) { 75 super(); 76 setArray(array); 77 } 78 79 89 public ArrayIterator(final Object array, final int startIndex) { 90 super(); 91 setArray(array); 92 checkBound(startIndex, "start"); 93 this.startIndex = startIndex; 94 this.index = startIndex; 95 } 96 97 108 public ArrayIterator(final Object array, final int startIndex, final int endIndex) { 109 super(); 110 setArray(array); 111 checkBound(startIndex, "start"); 112 checkBound(endIndex, "end"); 113 if (endIndex < startIndex) { 114 throw new IllegalArgumentException ("End index must not be less than start index."); 115 } 116 this.startIndex = startIndex; 117 this.endIndex = endIndex; 118 this.index = startIndex; 119 } 120 121 128 protected void checkBound(final int bound, final String type ) { 129 if (bound > this.endIndex) { 130 throw new ArrayIndexOutOfBoundsException ( 131 "Attempt to make an ArrayIterator that " + type + 132 "s beyond the end of the array. " 133 ); 134 } 135 if (bound < 0) { 136 throw new ArrayIndexOutOfBoundsException ( 137 "Attempt to make an ArrayIterator that " + type + 138 "s before the start of the array. " 139 ); 140 } 141 } 142 143 150 public boolean hasNext() { 151 return (index < endIndex); 152 } 153 154 161 public Object next() { 162 if (hasNext() == false) { 163 throw new NoSuchElementException (); 164 } 165 return Array.get(array, index++); 166 } 167 168 173 public void remove() { 174 throw new UnsupportedOperationException ("remove() method is not supported"); 175 } 176 177 186 public Object getArray() { 187 return array; 188 } 189 190 203 public void setArray(final Object array) { 204 this.endIndex = Array.getLength(array); 210 this.startIndex = 0; 211 this.array = array; 212 this.index = 0; 213 } 214 215 218 public void reset() { 219 this.index = this.startIndex; 220 } 221 222 } 223 | Popular Tags |