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.Month; 007 008 /** 009 * Defines iterator for month interval. 010 * 011 * @author Hongbing Kou 012 */ 013 public class MonthIterator implements Iterator<Month> { 014 /** End month. */ 015 private final Month endMonth; 016 /** Current month. */ 017 private Month currentMonth; 018 019 /** 020 * Creates an iterator. 021 * 022 * @param monthInterval Month Interval. 023 */ 024 MonthIterator(MonthInterval monthInterval) { 025 Month startMonth = monthInterval.getStartMonth(); 026 this.endMonth = monthInterval.getEndMonth(); 027 this.currentMonth = startMonth.dec(); 028 } 029 030 /** 031 * Gets the next month. 032 * 033 * @return Next month. 034 */ 035 public Month next() { 036 this.currentMonth = this.currentMonth.inc(); 037 038 if (this.currentMonth.compareTo(this.endMonth) > 0) { 039 throw new NoSuchElementException("Reaches the end of month interval already."); 040 } 041 042 return this.currentMonth; 043 } 044 045 /** 046 * If it is before the end month it will be a good one. 047 * 048 * @return Run our of interval or not. 049 */ 050 public boolean hasNext() { 051 return this.currentMonth.compareTo(this.endMonth) < 0; 052 } 053 054 /** 055 * Required for iterator(). It will throw UnSupportedMethodException. 056 */ 057 public void remove() { 058 throw new UnsupportedOperationException("remove() is not supported by month iterator."); 059 } 060 }