我想声明一个枚举方向,它有一个返回相反方向的方法(下面的语法不正确,即枚举不能被实例化,但它说明了我的观点)。这在Java中是可能的吗?
代码如下:
public enum Direction {
NORTH(1),
SOUTH(-1),
EAST(-2),
WEST(2);
Direction(int code){
this.code=code;
}
protected int code;
public int getCode() {
return this.code;
}
static Direction getOppositeDirection(Direction d){
return new Direction(d.getCode() * -1);
}
}
发布于 2013-09-19 07:06:24
对于这样的小枚举,我发现最具可读性的解决方案是:
public enum Direction {
NORTH {
@Override
public Direction getOppositeDirection() {
return SOUTH;
}
},
SOUTH {
@Override
public Direction getOppositeDirection() {
return NORTH;
}
},
EAST {
@Override
public Direction getOppositeDirection() {
return WEST;
}
},
WEST {
@Override
public Direction getOppositeDirection() {
return EAST;
}
};
public abstract Direction getOppositeDirection();
}
发布于 2014-11-20 01:50:10
这是可行的:
public enum Direction {
NORTH, SOUTH, EAST, WEST;
public Direction oppose() {
switch(this) {
case NORTH: return SOUTH;
case SOUTH: return NORTH;
case EAST: return WEST;
case WEST: return EAST;
}
throw new RuntimeException("Case not implemented");
}
}
发布于 2013-09-19 07:04:12
创建一个抽象方法,并让每个枚举值覆盖它。因为您在创建它时知道相反的情况,所以不需要动态地生成或创建它。
不过,它读起来不太好;也许switch
会更易于管理?
public enum Direction {
NORTH(1) {
@Override
public Direction getOppositeDirection() {
return Direction.SOUTH;
}
},
SOUTH(-1) {
@Override
public Direction getOppositeDirection() {
return Direction.NORTH;
}
},
EAST(-2) {
@Override
public Direction getOppositeDirection() {
return Direction.WEST;
}
},
WEST(2) {
@Override
public Direction getOppositeDirection() {
return Direction.EAST;
}
};
Direction(int code){
this.code=code;
}
protected int code;
public int getCode() {
return this.code;
}
public abstract Direction getOppositeDirection();
}
https://stackoverflow.com/questions/18883646
复制相似问题