2.在enum中定义方法和变量,比如我们可以为Color增加一个方法随机返回一个颜色。
public enum Color {
Red,
Green,
Blue;
/*
*定义一个变量表示枚举值的数目。
*(我有点奇怪为什么sun没有给enum直接提供一个size方法).
*/
private static int number = Color.values().length ;
/**
* 随机返回一个枚举值
@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;
}
}
}
6.定义枚举值自己的方法。
前面我们看到可以为enum定义一些方法,其实我们甚至可以为每一个枚举值定义方法。这样,我们前面覆载 toString的例子可以被改写成这样。
public enum Color {
Red {
public String toString(){
return "Color.Red";
}
},
Green {
public String toString(){
return "Color.Green";
}
},
Blue{
public String toString(){
return "Color.Blue";
}
public class Enum implements Enumeration{
/**
* Tests if this enumeration contains more elements.
*
* @return <code>true</code> if and only if this enumeration object
* contains at least one more element to provide;
* <code>false</code> otherwise.
*/
public boolean hasMoreElements() {
return false;
}
/**
* Returns the next element of this enumeration if this enumeration
* object has at least one more element to provide.
*
* @return the next element of this enumeration.
* @throws java.util.NoSuchElementException
* if no more elements exist.
*/
public Object nextElement() {
return null;
}
}
//这是一个枚举类型的写法
public class Enum {
public static final Enum ONE = new Enum("ONE",1);
public static final Enum TWO = new Enum("TWO",2);
public static final Enum THREE = new Enum("THREE",3);
public static final Enum FOUR = new Enum("FOUR",4);
private final String myName; // for debug only
private int value;