首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Java枚举方法-返回相反方向的枚举

Java枚举方法-返回相反方向的枚举
EN

Stack Overflow用户
提问于 2013-09-19 06:55:17
回答 5查看 159.2K关注 0票数 114

我想声明一个枚举方向,它有一个返回相反方向的方法(下面的语法不正确,即枚举不能被实例化,但它说明了我的观点)。这在Java中是可能的吗?

代码如下:

代码语言:javascript
复制
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);
     }
}
EN

回答 5

Stack Overflow用户

发布于 2013-09-19 07:06:24

对于这样的小枚举,我发现最具可读性的解决方案是:

代码语言:javascript
复制
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();

}
票数 164
EN

Stack Overflow用户

发布于 2014-11-20 01:50:10

这是可行的:

代码语言:javascript
复制
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");
    }
}
票数 29
EN

Stack Overflow用户

发布于 2013-09-19 07:04:12

创建一个抽象方法,并让每个枚举值覆盖它。因为您在创建它时知道相反的情况,所以不需要动态地生成或创建它。

不过,它读起来不太好;也许switch会更易于管理?

代码语言:javascript
复制
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();
}
票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18883646

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档