1. 程式人生 > >java enum無法賦初始值

java enum無法賦初始值

各位大蝦,想問一個有關的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吧。

  • bruni使用者頭像
  • bruni
  • (不如你)
  • 等 級:

#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不能實現嗎

  • sagezk使用者頭像
  • (SAGEZK)
  • 等 級:

#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