this code still missing some interesting features of Enum:
- missing "values()" as Iterator over all enum values
- still missing Ranged Iterator
- cannot be used in switch
Example
public final class Day implements Serializable {
private static final long serialVersionUID = 1L;
private static Day[] instances = new Day[7];
public static final Day MONDAY = new Day("Monday");
public static final Day TUESDAY = new Day("Tuesday");
public static final Day WEDNESDAY = new Day("Wednesday");
public static final Day THURSDAY = new Day("Thursday");
public static final Day FRIDAY = new Day("Friday");
public static final Day SATURDAY = new Day("Saturday");
public static final Day SUNDAY = new Day("Sunday");
private static int nextOrdinal = 0;
private transient final String name;
private final int ordinal;
private Day(String aName) {
this.name = aName;
this.ordinal = nextOrdinal++;
instances[this.ordinal] = this;
}
private Object readResolve() throws ObjectStreamException {
return instances[this.ordinal];
}
public String toString() {
return name;
}
public boolean equals(Object obj) {
return obj instanceof Day && ((Day) obj).ordinal == ordinal;
}
public int hashCode() {
return name.hashCode();
}
public static Iterator values() {
return new Iterator() {
private int i = 0;
public boolean hasNext() {
return i < instances.length;
}
public Object next() {
return instances[i++];
}
public void remove() {
throw new UnsupportedOperationException("Not supported.");
}
};
}
public static Iterator range(final Day from, final Day to) {
return new Iterator() {
private int i = from.ordinal;
public boolean hasNext() {
return i <= to.ordinal;
}
public Object next() {
return instances[i++];
}
public void remove() {
throw new UnsupportedOperationException("Not supported.");
}
};
}
public static void main(String[] args) {
Iterator week = Day.values();
while (week.hasNext()) {
System.out.println(week.next());
}
Iterator weekEnd = Day.range(SATURDAY, SUNDAY);
while (weekEnd.hasNext()) {
System.out.println(weekEnd.next());
}
}
}