1 9 package javolution.lang; 10 11 import j2me.io.Serializable; 12 import j2me.lang.Comparable; 13 import j2mex.realtime.MemoryArea; 14 15 import javolution.util.FastMap; 16 17 27 public abstract class Enum implements Comparable , Serializable { 28 29 32 private static final FastMap CLASS_TO_ENUMS = new FastMap(); 33 34 37 private final String _name; 38 39 42 private final int _ordinal; 43 44 49 public final String name() { 50 return _name; 51 } 52 53 59 public final int ordinal() { 60 return _ordinal; 61 } 62 63 69 protected Enum(String name, int ordinal) { 70 _name = name; 71 _ordinal = ordinal; 72 synchronized (CLASS_TO_ENUMS) { 73 MemoryArea.getMemoryArea(CLASS_TO_ENUMS).executeInArea( 74 new Runnable () { 75 public void run() { 76 FastMap nameToEnum = (FastMap) CLASS_TO_ENUMS 77 .get(Enum.this.getClass()); 78 if (nameToEnum == null) { 79 nameToEnum = new FastMap(); 80 CLASS_TO_ENUMS.put(Enum.this.getClass(), 81 nameToEnum); 82 } 83 Object prev = nameToEnum.put(_name, Enum.this); 84 if (prev != null) { 85 throw new IllegalArgumentException ( 86 "Duplicate enum " + _name); 87 } 88 } 89 }); 90 } 91 } 92 93 98 public String toString() { 99 return _name; 100 } 101 102 108 public final boolean equals(Object that) { 109 return this == that; 110 } 111 112 117 public final int hashCode() { 118 return System.identityHashCode(this); 119 } 120 121 130 public final int compareTo(Object that) { 131 Enum e = (Enum ) that; 132 if (this.getClass() == that.getClass()) { 133 return this._ordinal - e._ordinal; 134 } else { 135 throw new ClassCastException (); 136 } 137 } 138 139 144 public final Class getDeclaringClass() { 145 return this.getClass(); 146 } 147 148 157 public static Enum valueOf(Class enumType, String name) { 158 FastMap nameToEnum = (FastMap) CLASS_TO_ENUMS.get(enumType); 159 if (nameToEnum != null) { 160 Enum e = (Enum ) nameToEnum.get(name); 161 if (e != null) { 162 return e; 163 } 164 } 165 throw new IllegalArgumentException (enumType + "." + name + " not found"); 166 } 167 168 } | Popular Tags |