1 16 package org.apache.commons.collections.iterators; 17 18 import java.util.List ; 19 import java.util.ListIterator ; 20 import java.util.NoSuchElementException ; 21 22 import org.apache.commons.collections.ResettableListIterator; 23 24 41 public class LoopingListIterator implements ResettableListIterator { 42 43 44 private List list; 45 46 private ListIterator iterator; 47 48 58 public LoopingListIterator(List list) { 59 if (list == null) { 60 throw new NullPointerException ("The list must not be null"); 61 } 62 this.list = list; 63 reset(); 64 } 65 66 74 public boolean hasNext() { 75 return !list.isEmpty(); 76 } 77 78 86 public Object next() { 87 if (list.isEmpty()) { 88 throw new NoSuchElementException ( 89 "There are no elements for this iterator to loop on"); 90 } 91 if (iterator.hasNext() == false) { 92 reset(); 93 } 94 return iterator.next(); 95 } 96 97 108 public int nextIndex() { 109 if (list.isEmpty()) { 110 throw new NoSuchElementException ( 111 "There are no elements for this iterator to loop on"); 112 } 113 if (iterator.hasNext() == false) { 114 return 0; 115 } else { 116 return iterator.nextIndex(); 117 } 118 } 119 120 128 public boolean hasPrevious() { 129 return !list.isEmpty(); 130 } 131 132 141 public Object previous() { 142 if (list.isEmpty()) { 143 throw new NoSuchElementException ( 144 "There are no elements for this iterator to loop on"); 145 } 146 if (iterator.hasPrevious() == false) { 147 Object result = null; 148 while (iterator.hasNext()) { 149 result = iterator.next(); 150 } 151 iterator.previous(); 152 return result; 153 } else { 154 return iterator.previous(); 155 } 156 } 157 158 169 public int previousIndex() { 170 if (list.isEmpty()) { 171 throw new NoSuchElementException ( 172 "There are no elements for this iterator to loop on"); 173 } 174 if (iterator.hasPrevious() == false) { 175 return list.size() - 1; 176 } else { 177 return iterator.previousIndex(); 178 } 179 } 180 181 199 public void remove() { 200 iterator.remove(); 201 } 202 203 218 public void add(Object obj) { 219 iterator.add(obj); 220 } 221 222 234 public void set(Object obj) { 235 iterator.set(obj); 236 } 237 238 241 public void reset() { 242 iterator = list.listIterator(); 243 } 244 245 250 public int size() { 251 return list.size(); 252 } 253 254 } 255 | Popular Tags |