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

2023-12-12

我想声明一个枚举 Direction,它有一个返回相反方向的方法(以下内容在语法上不正确,即枚举无法实例化,但它说明了我的观点)。这在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);
     }
}

对于那些被标题吸引到这里的人:是的,你can在枚举中定义您自己的方法。

如果您想知道如何调用自己的非静态枚举方法,您可以按照与任何其他非静态方法相同的方式进行操作 - 您可以在instance定义/继承此类方法的类型。

对于枚举来说,这种情况很简单ENUM_VALUE他们自己。

所以你需要的是YourEnum.YOUR_ENUM_VALUE.yourMethod(arguments).


现在让我们从问题回到问题。解决方案之一可能是

public enum Direction {
    
    NORTH, SOUTH, EAST, WEST;
    
    private Direction opposite;
    
    static {
        NORTH.opposite = SOUTH;
        SOUTH.opposite = NORTH;
        EAST.opposite = WEST;
        WEST.opposite = EAST;
    }
    
    public Direction getOppositeDirection() {
        return opposite;
    }
    
}

Now Direction.NORTH.getOppositeDirection()将返回Direction.SOUTH.


这是更“hacky”的方式来说明@jedwards 评论但它感觉不像第一种方法那么灵活,因为添加更多字段或更改它们的顺序会破坏我们的代码。

public enum Direction {
    NORTH, EAST, SOUTH, WEST;
    
    // cached values to avoid recreating such array each time method is called
    private static final Direction[] VALUES = values();

    public Direction getOppositeDirection() {
        return VALUES[(ordinal() + 2) % 4]; 
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java Enum 方法 - 返回相反方向的枚举 的相关文章

随机推荐