各位大虾,想问一个有关的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里怎么实现,在网上找了很久也没答案,在这里提问出来,希望能有答案,谢谢各位。
在.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里怎么实现,在网上找了很久也没答案,在这里提问出来,希望能有答案,谢谢各位。
一定要这样的话,那还是老办法static final吧。
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");
}
}
}
}
...
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;
}
}
如果你一定要用enum,那就把那个数组声明为enum类型。
是这个道理不?没必要简单问题复杂化。
public static final int NONE = 0xff, UP = 2, DOWN = 4, LEFT = 8, RIGHT = 16
Java没有进入enum之前这种用法遍地都是。
而且我觉得你的情况本来就不适合用enum。
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 class T{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String input = in.next();
Direction dir = Enum.valueOf(Direction.class, input);
switch (dir) {
case None:
System.out.println("None");
break;
case Up:
System.out.println("Up");
break;
}
}}还有一点要说的是,虽然说,JAVA默认的0,1,2,3,但是可以改变,详见JDK1.6