public enum Color { Red, Green, Blue; /* *定义一个变量表C枚丑ր的数目?br /> *(我有点奇怪ؓ(f)什么sun没有lenum直接提供一个sizeҎ(gu)). */ private static int number = Color.values().length ; /** * 随机q回一个枚丑ր?br /> @return a random enum value. */ public static Color getRandomColor(){ long random = System.currentTimeMillis() % number; switch ((int) random){ case 0: return Color.Red; case 1: return Color.Green; case 2: return Color.Blue; default : return Color.Red; } } } |
? public String toString(){ switch (this){ case Red: return "Color.Red"; case Green: return "Color.Green"; case Blue: return "Color.Blue"; default: return "Unknow Color"; } } ? |
public enum Color { Red("This is Red"), Green("This is Green"), Blue("This is Blue"); private String desc; Color(String desc){ this.desc = desc; } public String getDesc(){ return this.desc; } } |
public enum Color { Red { public String toString(){ return "Color.Red"; } }, Green { public String toString(){ return "Color.Green"; } }, Blue{ public String toString(){ return "Color.Blue"; } }; } |
protected Object initialValue() { return null; } |
public class ThreadLocal { private Map values = Collections.synchronizedMap(new HashMap()); public Object get() { Thread curThread = Thread.currentThread(); Object o = values.get(curThread); if (o == null && !values.containsKey(curThread)) { o = initialValue(); values.put(curThread, o); } return o; } public void set(Object newValue) { values.put(Thread.currentThread(), newValue); } public Object initialValue() { return null; } } |
public class SerialNum { // The next serial number to be assigned private static int nextSerialNum = 0; private static ThreadLocal serialNum = new ThreadLocal() { protected synchronized Object initialValue() { return new Integer(nextSerialNum++); } }; public static int get() { return ((Integer) (serialNum.get())).intValue(); } } |
int serial = SerialNum.get(); |