各位大蝦,想問一個有關的java enum 問題
在.net 中 enum元素可以賦值如:
enum Direction { None = 0xff, Up = 2, Down = 4, Left = 8, Right = 16 };
但java里是默認元素為0 1 2 3,在java怎么樣才能達到以上效果。如有一段.net 代碼:
......
enum Direction { None = 0xff, Up = 2, Down = 4, Left = 8, Right = 16 };
...
switch (i[x, y])
{
case (int)Direction.Left:
x--;
break;
case (int)Direction.Right:
x++;
break;
case (int)Direction.Up:
y--;
break;
case (int)Direction.Down:
y++;
break;
case (int)Direction.None:
return;
}
這段代碼在java里怎么實現,在網上找了很久也沒答案,在這里提問出來,希望能有答案,謝謝各位。
#1樓 得分:0回復于:2008-11-11 00:28:04
不明白,既然用了enum,為什么還要要用數字來判斷呢?
一定要這樣的話,那還是老辦法static final吧。
#2樓 得分:10回復于:2008-11-11 00:33:13
- Java code
public enum Direction {
None(0xff), Up(2), Down (4), Left( 8), Right (16);
private final int value;
/**
* Constructor.
*/
private Direction(int value) {
this.value = value;
}
/**
* Get the value.
* @return the value
*/
public int getValue() {
return value;
}
public static void main(String args[]) throws Exception {
Direction[] arr = {None, Up, Down, Left, Right};
for (int i = 0; i < arr.length; i++) {
switch(arr[i]) {
case None: System.out.println("None");
case Up: System.out.println("Up");
case Down: System.out.println("Down");
case Left: System.out.println("Left");
case Right: System.out.println("Right");
default: System.out.println("Nothing to match");
}
}
}
}
#3樓 得分:0回復于:2008-11-11 00:33:28
因為i數組存的是數字,java里的enum不能實現嗎
#4樓 得分:10回復于:2008-11-11 00:44:40
.NET 和 Java 枚舉的實現原理不太一樣,如果拿 Java 寫上面代碼,可以按下面方式寫:
- Java code
public enum Direction {UP, DOWN, LEFT, RIGHT} //Java 中習慣于把枚舉常量寫成全大寫字符的形式
Direction[][] i = new Direction[100][100];
...
if (i[x][y] != null) { //Java 中枚舉類型的變量可以取值為 null,所以可以用 null 表示 None 即無方向
switch (i[x][y]) {
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
case UP:
y--;
break;
case DOWN:
y++;
break;
}
}
#5樓 得分:0回復于:2008-11-11 00:56:21
不要為了用enum而用enum,既然你要判斷是int,那就用int,沒必要非用enum不可。
如果你一定要用enum,那就把那個數組聲明為enum類型。
是這個道理不?沒必要簡單問題復雜化。
#6樓 得分:0回復于:2008-11-11 01:17:08
這里說明一下,i數組存的是很多數字,是模仿迷宮存放數字用的,當然可以不用enum,swith里可以數字,但這樣可讀性是不是比較差,因為enum里存的是方向,如果用數字判斷,別人看了就不知這些數字是什么來的
#7樓 得分:0回復于:2008-11-11 01:24:27
4樓的大哥,case LEFT://這里的LEFT可以轉為數字嗎,因為i數組存的是數字,不是很明白java的enum