import java.util.Vector; import java.util.Enumeration; /** TypeSafeEnum base class for building type safe enumeration subclasses. */ public class TypeSafeEnum { private static class enumInfo { public int hashCode; public int count; public Vector values; enumInfo( int hash ) { hashCode = hash; count = 0; values = new Vector(); } } // class enumInfo private static Vector infoVec = new Vector(); private String mName; private int mValue; public TypeSafeEnum( String name, Class cls ) { mName = name; enumInfo elem = findInfo( cls, true ); mValue = elem.count; elem.count++; elem.values.add( this ); } // TypeSafeEnum constructor public static Enumeration enumValues( Class cls ) { Enumeration e = null; enumInfo elem = findInfo( cls, false ); if (elem != null) { e = elem.values.elements(); } return e; } // enumValues public String getName() { return mName; } public int getValue() { return mValue; } /** Find the entry for the enumeration, if it exists. If not, add it to the end of the enumInfo. Note that this function has linear time, but the assumption is that there will not a large number of enumeration classes. */ private static enumInfo findInfo(Class cls, boolean add) { enumInfo foundElem = null; int hashCode = cls.hashCode(); for (Enumeration e = infoVec.elements(); e.hasMoreElements(); ) { enumInfo elem = (enumInfo)e.nextElement(); if (elem.hashCode == hashCode) { foundElem = elem; break; } } if (foundElem == null && add) { foundElem = new enumInfo(hashCode); infoVec.add( foundElem ); } return foundElem; } // findInfo }