001 package org.hackystat.utilities.time.interval; 002 003 import java.util.Iterator; 004 import java.util.NoSuchElementException; 005 006 import org.hackystat.utilities.time.period.Day; 007 008 /** 009 * Provides an iterator over Day instances. 010 * 011 * @author Hongbing Kou, Philip Johnson 012 */ 013 public class DayIterator implements Iterator<Day> { 014 /** End day of the day interval. */ 015 private final Day endDay; 016 /** Current day. */ 017 private Day currentDay; 018 019 /** 020 * Creates a day iterator over the interval. 021 * 022 * @param dayInterval Iterator over the day. 023 */ 024 DayIterator(DayInterval dayInterval) { 025 Day startDay = dayInterval.getStartDay(); 026 this.endDay = dayInterval.getEndDay(); 027 this.currentDay = startDay.inc(-1); 028 } 029 030 /** 031 * Required for iterator(). It will throw UnSupportedMethodException. 032 */ 033 public void remove() { 034 throw new UnsupportedOperationException("remove() is not supported by day iterator."); 035 } 036 037 /** 038 * Whether it is still inside the day interval. 039 * 040 * @return True if it is still in the interval. 041 */ 042 public boolean hasNext() { 043 return this.currentDay.compareTo(this.endDay) < 0; 044 } 045 046 /** 047 * Gets the next day. 048 * 049 * @return Next day. 050 */ 051 public Day next() { 052 this.currentDay = this.currentDay.inc(1); 053 054 if (this.currentDay.compareTo(this.endDay) > 0) { 055 throw new NoSuchElementException("Reaches the end of day interval already."); 056 } 057 058 return this.currentDay; 059 } 060 }